-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPattern.cs
More file actions
630 lines (580 loc) · 22.2 KB
/
Pattern.cs
File metadata and controls
630 lines (580 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
using System;
using System.Runtime.Remoting.Contexts;
using System.Text;
namespace ReadableRex.Patterns
{
/// <summary>
/// Represents a builder for constructing regular expression patterns.
/// </summary>
/// <remarks>The <see cref="Pattern"/> class provides a fluent interface for creating complex regular
/// expression patterns. It allows for the combination of various pattern elements, such as literals, character
/// classes, and quantifiers, into a single cohesive pattern. This class supports method chaining to facilitate the
/// construction of patterns in a readable and maintainable manner.</remarks>
public class Pattern
{
readonly StringBuilder _content;
/// <summary>
/// Indicates creation of a new pattern
/// </summary>
public static Pattern With
{
get
{
return new Pattern(String.Empty);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Pattern"/> class.
/// </summary>
public Pattern()
{
_content = new StringBuilder();
}
/// <summary>
/// Initializes a new instance of the <see cref="Pattern"/> class with the specified initial regular expression
/// content.
/// </summary>
/// <param name="initialRegexContent">The initial content for the regular expression. Cannot be <see langword="null"/>.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="initialRegexContent"/> is <see langword="null"/>.</exception>
internal Pattern(string initialRegexContent)
{
//Do we even need this public? Should we force everyone to use Pattern.With syntax?
if (initialRegexContent == null) throw new ArgumentNullException("initialRegexContent");
_content = new StringBuilder(initialRegexContent);
}
/// <summary>
/// Evaluates and returns the string representation of the current content.
/// </summary>
/// <returns>A string that represents the current content.</returns>
private string Eval()
{
return _content.ToString();
}
/// <summary>
/// Appends the specified literal strings to the pattern, escaping any reserved characters.
/// </summary>
/// <remarks>Reserved characters in regular expressions include: <c>.</c>, <c>$</c>, <c>^</c>,
/// <c>{</c>, <c>[</c>, <c>(</c>, <c>|</c>, <c>)</c>, <c>*</c>, <c>+</c>, <c>?</c>, and <c>\</c>. These
/// characters are automatically escaped in the appended strings.</remarks>
/// <param name="contents">An array of strings to be appended to the pattern. Each string is processed to escape characters that are
/// reserved in regular expressions.</param>
/// <returns>The current <see cref="Pattern"/> instance with the specified literals appended.</returns>
public Pattern Literal(params string[] contents)
{
string reservedCharacters = @".$^{[(|)*+?\";
foreach (var content in contents)
{
foreach (char character in content)
{
if (reservedCharacters.IndexOf(character) < 0)
{
_content.Append(character);
}
else
{
_content.Append('\\').Append(character);
}
}
}
return this;
}
/// <summary>
/// Any existing regular expression pattern.
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
public Pattern RegEx(string pattern)
{
_content.Append(pattern);
return this;
}
/// <summary>
/// Gets a pattern that matches any single character.
/// </summary>
/// <remarks>This property appends a wildcard character to the current pattern, allowing it to
/// match any single character.</remarks>
public Pattern Anything
{
get
{
_content.Append(@".");
return this;
}
}
/// <summary>
/// Gets a pattern that matches any word character.
/// </summary>
/// <remarks>A word character is typically any alphanumeric character or underscore. This property
/// appends the pattern for a word character to the current content.</remarks>
public Pattern Word
{
get
{
_content.Append(@"\w");
return this;
}
}
/// <summary>
/// Gets a pattern that matches any non-word character.
/// </summary>
public Pattern NonWord
{
get
{
_content.Append(@"\W");
return this;
}
}
/// <summary>
/// Gets a pattern that matches any digit character.
/// </summary>
public Pattern Digit
{
get
{
_content.Append(@"\d");
return this;
}
}
/// <summary>
/// Gets a pattern that matches any non-digit character.
/// </summary>
public Pattern NonDigit
{
get
{
_content.Append(@"\D");
return this;
}
}
/// <summary>
/// Gets a pattern that matches any whitespace character.
/// </summary>
public Pattern WhiteSpace
{
get
{
_content.Append(@"\s");
return this;
}
}
/// <summary>
/// Gets a pattern that matches any non-whitespace character.
/// </summary>
public Pattern NonWhiteSpace
{
get
{
_content.Append(@"\S");
return this;
}
}
/// <summary>
/// Gets a pattern that matches any hexadecimal digit (0-9, A-F, a-f).
/// </summary>
public Pattern HexDigit
{
get
{
_content.Append(@"[0-9A-Fa-f]");
return this;
}
}
/// <summary>
/// Appends a custom set of characters to the pattern.
/// </summary>
/// <param name="chars">The characters to include in the custom set. This string is enclosed in square brackets in the pattern.</param>
/// <returns>The current <see cref="Pattern"/> instance with the appended custom set.</returns>
public Pattern CustomSet(string chars)
{
_content.AppendFormat("[{0}]", chars);
return this;
}
/// <summary>
/// Gets a pattern that matches any letter (uppercase and lowercase).
/// </summary>
public Pattern AnyLetter
{
get
{
_content.Append(@"[a-zA-Z]");
return this;
}
}
/// <summary>
/// Gets a pattern that matches any lowercase letter.
/// </summary>
public Pattern AnyLowercaseLetter
{
get
{
_content.Append(@"[a-z]");
return this;
}
}
/// <summary>
/// Gets a pattern that matches any uppercase letter.
/// </summary>
public Pattern AnyUppercaseLetter
{
get
{
_content.Append(@"[A-Z]");
return this;
}
}
/// <summary>
/// Defines a character range pattern from the specified start and end characters.
/// </summary>
/// <remarks>The method appends a character range to the pattern, using the specified start and
/// end characters. If either character is a reserved regex character, it is automatically escaped.</remarks>
/// <param name="c1">The starting character of the range. Must not be a reserved regex character unless escaped.</param>
/// <param name="c2">The ending character of the range. Must not be a reserved regex character unless escaped.</param>
/// <returns>The current <see cref="Pattern"/> instance with the specified character range appended.</returns>
public Pattern Of(char c1, char c2)
{
string reservedCharacters = @".$^{[(|)*+?\";
_content.Append('[');
if (reservedCharacters.IndexOf(c1) < 0)
{
_content.Append(c1);
}
else
{
_content.Append('\\').Append(c1);
}
_content.Append('-'); // Add a hyphen to indicate a range
if (reservedCharacters.IndexOf(c2) < 0)
{
_content.Append(c2);
}
else
{
_content.Append('\\').Append(c2);
}
_content.Append("]");
return this;
}
/// <summary>
/// Defines a pattern that matches a range of integers.
/// </summary>
/// <param name="range">An array of integers specifying the range. The array must contain at least two integers, representing the
/// start and end of the range.</param>
/// <returns>The current <see cref="Pattern"/> instance with the specified integer range appended.</returns>
/// <exception cref="ArgumentException">Thrown if <paramref name="range"/> is null or contains fewer than two integers.</exception>
public Pattern OfInt(params int[] range)
{
if (range == null || range.Length < 2)
{
throw new ArgumentException("Range must contain at least two integers.");
}
_content.Append('[');
for (int i = 0; i < range.Length; i++)
{
if (i > 0) _content.Append('-'); // Add hyphen for range
_content.Append(range[i]);
}
_content.Append(']');
return this;
}
/// <summary>
/// Returns a string representation of the current object.
/// </summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return Eval();
}
/// <summary>
/// A subset of the pattern that can be referenced as ordinal captures
/// </summary>
/// <param name="innerExpression"></param>
/// <returns></returns>
public Pattern Group(Pattern innerExpression)
{
_content.AppendFormat("({0})", innerExpression.ToString());
return this;
}
/// <summary>
/// A subset of the pattern that can be referenced as a named capture
/// </summary>
/// <param name="groupName"></param>
/// <param name="innerExpression"></param>
/// <returns></returns>
public Pattern NamedGroup(string groupName, Pattern innerExpression)
{
_content.AppendFormat("(?<{1}>{0})", innerExpression.ToString(), groupName);
return this;
}
/// <summary>
/// A non-capturing group
/// </summary>
/// <param name="innerExpression"></param>
/// <returns></returns>
public Pattern Phrase(Pattern innerExpression)
{
_content.AppendFormat("(?:{0})", innerExpression.ToString());
return this;
}
/// <summary>
/// Matches any single character contained within
/// </summary>
/// <param name="innerExpression"></param>
/// <returns></returns>
public Pattern Set(Pattern innerExpression)
{
_content.AppendFormat("[{0}]", innerExpression.ToString());
return this;
}
/// <summary>
/// Matches any single character not contained within
/// </summary>
/// <param name="innerExpression"></param>
/// <returns></returns>
public Pattern NegatedSet(Pattern innerExpression)
{
_content.AppendFormat("[^{0}]", innerExpression.ToString());
return this;
}
/// <summary>
/// Quantifies how many times to detect the previous element
/// </summary>
public Quantifier Repeat
{
get
{
return new Quantifier(this);
}
}
/// <summary>
/// Determines whether the current instance is in a true state.
/// </summary>
/// <returns><see langword="true"/> if the current instance is in a true state; otherwise, <see langword="false"/>.</returns>
public bool IsTrue()
{
return true;
}
/// <summary>
/// Gets a pattern that matches case-insensitively.
/// </summary>
/// <remarks>Accessing this property modifies the pattern to perform case-insensitive matching by
/// prepending the case-insensitive flag "(?i)" to the pattern.</remarks>
public Pattern IgnoreCase
{
get
{
_content.Insert(0, "(?i)");
return this;
}
}
/// <summary>
/// Gets the pattern with multiline mode enabled.
/// </summary>
public Pattern Multiline
{
get
{
_content.Insert(0, "(?m)");
return this;
}
}
/// <summary>
/// Gets the pattern used to validate email addresses.
/// </summary>
public static Pattern Email
{
get
{
return new Pattern(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}");
}
}
/// <summary>
/// Specifies that the match must occur at the beginning of the string or the beginning of the line
/// </summary>
public Pattern StartsWith
{
get
{
_content.Append('^');
return this;
}
}
/// <summary>
/// Specifies that the match must occur at the end of the string, before \n at the end of the string, or at the end of the line.
/// </summary>
public Pattern EndOfString
{
get
{
_content.Append('$');
return this;
}
}
/// <summary>
/// Gets a pattern that matches the start of a line, optionally preceded by a newline character.
/// </summary>
public Pattern StartOfLine
{
get
{
_content.Append(@"^\n?");
return this;
}
}
/// <summary>
/// Gets the pattern that matches the end of a line.
/// </summary>
public Pattern EndOfLine
{
get
{
_content.Append(@"\n?$");
return this;
}
}
/// <summary>
/// Gets a pattern that matches a word boundary in a regular expression.
/// </summary>
/// <remarks>This property appends the word boundary pattern <c>\b</c> to the current regular
/// expression pattern.</remarks>
public Pattern WordBoundary
{
get
{
_content.Append(@"\b");
return this;
}
}
/// <summary>
/// Gets a pattern that matches a non-word boundary in a regular expression.
/// </summary>
/// <remarks>A non-word boundary is a position in the input string where a word character is not
/// adjacent to another word character. This property appends the non-word boundary pattern <c>\B</c> to the
/// current pattern.</remarks>
public Pattern NonWordBoundary
{
get
{
_content.Append(@"\B");
return this;
}
}
/// <summary>
/// Specifies that the preceding element must occur at least a minimum number of times and at most a maximum
/// number of times.
/// </summary>
/// <param name="min">The minimum number of times the preceding element must occur. Must be non-negative.</param>
/// <param name="max">The maximum number of times the preceding element can occur. Must be greater than or equal to <paramref
/// name="min"/>.</param>
/// <returns>The current <see cref="Pattern"/> instance with the specified repetition constraints applied.</returns>
public Pattern ExactlyBetween(int min, int max)
{
_content.AppendFormat("{{{0},{1}}}", min, max);
return this;
}
/// <summary>
/// Appends a comment to the pattern.
/// </summary>
/// <param name="text">The comment text to include in the pattern. This text should not contain any special regex characters.</param>
/// <returns>The current <see cref="Pattern"/> instance with the appended comment.</returns>
public Pattern Comment(string text)
{
_content.AppendFormat("(?# {0})", text);
return this;
}
/// <summary>
/// Converts a <see cref="Pattern"/> object to its string representation.
/// </summary>
/// <param name="expression">The <see cref="Pattern"/> instance to convert.</param>
public static implicit operator string(Pattern expression)
{
return expression.ToString();
}
/// <summary>
/// Concatenates two <see cref="Pattern"/> instances, appending the second pattern to the first.
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public static Pattern operator +(Pattern first, Pattern second)
{
first._content.Append(second.ToString());
return first;
}
/// <summary>
/// Appends a positive lookahead assertion to the current pattern.
/// </summary>
/// <remarks>A positive lookahead is a zero-width assertion that ensures a certain pattern can be
/// matched ahead in the input without consuming any characters. This method modifies the current pattern to
/// include the specified lookahead condition.</remarks>
/// <param name="inner">The pattern to be used as the positive lookahead condition.</param>
/// <returns>The current <see cref="Pattern"/> instance with the appended positive lookahead.</returns>
public Pattern PositiveLookahead(Pattern inner)
{
_content.AppendFormat("(?={0})", inner);
return this;
}
/// <summary>
/// Appends a negative lookahead assertion to the current pattern.
/// </summary>
/// <remarks>A negative lookahead assertion ensures that the specified pattern does not match at
/// the current position. This method modifies the current pattern to include the negative lookahead, allowing
/// for complex pattern matching scenarios where certain sequences must not be present.</remarks>
/// <param name="inner">The pattern to be used in the negative lookahead assertion.</param>
/// <returns>The current <see cref="Pattern"/> instance with the negative lookahead appended.</returns>
public Pattern NegativeLookahead(Pattern inner)
{
_content.AppendFormat("(?!{0})", inner);
return this;
}
/// <summary>
/// Appends a positive lookbehind assertion to the current pattern.
/// </summary>
/// <remarks>A positive lookbehind assertion ensures that the specified pattern precedes the
/// current position in the input string. The lookbehind pattern must be of fixed length, as variable-length
/// lookbehinds are not supported.</remarks>
/// <param name="inner">The pattern to be used as the lookbehind assertion. This pattern must be fixed-width.</param>
/// <returns>The current <see cref="Pattern"/> instance with the appended lookbehind assertion.</returns>
public Pattern PositiveLookbehind(Pattern inner)
{
_content.AppendFormat("(?<={0})", inner);
return this;
}
/// <summary>
/// Appends a negative lookbehind assertion to the current pattern.
/// </summary>
/// <remarks>A negative lookbehind assertion ensures that the specified pattern does not precede
/// the current position in the input string.</remarks>
/// <param name="inner">The pattern to be used in the negative lookbehind assertion.</param>
/// <returns>The current <see cref="Pattern"/> instance with the negative lookbehind assertion appended.</returns>
public Pattern NegativeLookbehind(Pattern inner)
{
_content.AppendFormat("(?<!{0})", inner);
return this;
}
/// <summary>
/// Gets an <see cref="Alternation"/> instance representing a choice based on the current context.
/// </summary>
public Alternation Choice
{
get
{
return new Alternation(this);
}
}
/// <summary>
/// Creates a new pattern that matches either the current pattern or the specified pattern.
/// </summary>
/// <remarks>This method uses a non-capturing group to combine the patterns, allowing for
/// alternation without capturing the matched text.</remarks>
/// <param name="other">The pattern to combine with the current pattern using alternation.</param>
/// <returns>A new <see cref="Pattern"/> that matches either the current pattern or the specified <paramref
/// name="other"/> pattern.</returns>
public Pattern Or(Pattern other)
{
// Wrap current and other pattern in a non-capturing group with alternation
var combined = $"(?:{ToString()}|{other})";
return new Pattern(combined);
}
}
}