/
Regex.KnownPattern.Tests.cs
1472 lines (1271 loc) · 65.8 KB
/
Regex.KnownPattern.Tests.cs
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
namespace System.Text.RegularExpressions.Tests
{
public class RegexKnownPatternTests
{
//
// These patterns come from the Regex documentation at docs.microsoft.com.
//
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-example-scanning-for-hrefs
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_Examples_ScanningHrefs(RegexEngine engine)
{
const string HrefPattern =
@"href\s*=\s*(?:[""'](?<1>[^""']*)[""']|(?<1>\S+))";
const string InputString =
"My favorite web sites include:</P>" +
"<A HREF=\"http://msdn2.microsoft.com\">" +
"MSDN Home Page</A></P>" +
"<A HREF=\"http://www.microsoft.com\">" +
"Microsoft Corporation Home Page</A></P>" +
"<A HREF=\"http://blogs.msdn.com/bclteam\">" +
".NET Base Class Library blog</A></P>";
Regex r = await RegexHelpers.GetRegexAsync(engine, HrefPattern, RegexOptions.IgnoreCase);
Match m = r.Match(InputString);
Assert.True(m.Success);
if (!RegexHelpers.IsNonBacktracking(engine))
{
Assert.Equal("http://msdn2.microsoft.com", m.Groups[1].ToString());
Assert.Equal(43, m.Groups[1].Index);
}
m = m.NextMatch();
Assert.True(m.Success);
if (!RegexHelpers.IsNonBacktracking(engine))
{
Assert.Equal("http://www.microsoft.com", m.Groups[1].ToString());
Assert.Equal(102, m.Groups[1].Index);
}
m = m.NextMatch();
Assert.True(m.Success);
if (!RegexHelpers.IsNonBacktracking(engine))
{
Assert.Equal("http://blogs.msdn.com/bclteam", m.Groups[1].ToString());
Assert.Equal(176, m.Groups[1].Index);
}
m = m.NextMatch();
Assert.False(m.Success);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-example-changing-date-formats
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_Examples_MDYtoDMY(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// named group replacements not supported
return;
}
Regex r = await RegexHelpers.GetRegexAsync(engine, @"\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b");
string dt = new DateTime(2020, 1, 8, 0, 0, 0, DateTimeKind.Utc).ToString("d", DateTimeFormatInfo.InvariantInfo);
Assert.Equal("08-01-2020", r.Replace(dt, "${day}-${month}-${year}"));
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-extract-a-protocol-and-port-number-from-a-url
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_Examples_ExtractProtocolPort(RegexEngine engine)
{
Regex r = await RegexHelpers.GetRegexAsync(engine, @"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/");
Match m = r.Match("http://www.contoso.com:8080/letters/readme.html");
Assert.True(m.Success);
if (!RegexHelpers.IsNonBacktracking(engine))
{
Assert.Equal("http:8080", m.Result("${proto}${port}"));
}
}
public static IEnumerable<object[]> Docs_Examples_ValidateEmail_TestData()
{
foreach (RegexEngine engine in RegexHelpers.AvailableEngines)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// The email pattern uses conditional test-patterns so NonBacktracking is not supported here
continue;
}
yield return new object[] { engine, "david.jones@proseware.com", true };
yield return new object[] { engine, "d.j@server1.proseware.com", true };
yield return new object[] { engine, "jones@ms1.proseware.com", true };
yield return new object[] { engine, "j.@server1.proseware.com", false };
yield return new object[] { engine, "j@proseware.com9", true };
yield return new object[] { engine, "js#internal@proseware.com", true };
yield return new object[] { engine, "j_9@[129.126.118.1]", true };
yield return new object[] { engine, "j..s@proseware.com", false };
yield return new object[] { engine, "js*@proseware.com", false };
yield return new object[] { engine, "js@proseware..com", false };
yield return new object[] { engine, "js@proseware.com9", true };
yield return new object[] { engine, "j.s@server1.proseware.com", true };
yield return new object[] { engine, "\"j\\\"s\\\"\"@proseware.com", true };
yield return new object[] { engine, "js@contoso.\u4E2D\u56FD", true };
}
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format
[Theory]
[MemberData(nameof(Docs_Examples_ValidateEmail_TestData))]
public async Task Docs_Examples_ValidateEmail(RegexEngine engine, string email, bool expectedIsValid)
{
Assert.Equal(expectedIsValid, await IsValidEmailAsync(email, engine));
async Task<bool> IsValidEmailAsync(string email, RegexEngine engine)
{
if (string.IsNullOrWhiteSpace(email))
{
return false;
}
try
{
Regex r = await RegexHelpers.GetRegexAsync(engine, @"(@)(.+)$", RegexOptions.None, TimeSpan.FromMilliseconds(200));
// Normalize the domain part of the email
email = r.Replace(email, match =>
{
// Use IdnMapping class to convert Unicode domain names.
var idn = new IdnMapping();
// Pull out and process domain name (throws ArgumentException on invalid)
string domainName = idn.GetAscii(match.Groups[2].Value);
return match.Groups[1].Value + domainName;
});
}
catch (RegexMatchTimeoutException)
{
return false;
}
catch (ArgumentException)
{
return false;
}
try
{
Regex r = await RegexHelpers.GetRegexAsync(
engine,
@"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase,
TimeSpan.FromMilliseconds(250));
return r.IsMatch(email);
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions#matched_subexpression
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_GroupingConstructs_MatchedSubexpression(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// backreferences not supported
return;
}
const string Pattern = @"(\w+)\s(\1)";
const string Input = "He said that that was the the correct answer.";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern, RegexOptions.IgnoreCase);
Match match = r.Match(Input);
Assert.True(match.Success);
Assert.Equal("that", match.Groups[1].Value);
Assert.Equal(8, match.Groups[1].Index);
Assert.Equal(13, match.Groups[2].Index);
match = match.NextMatch();
Assert.True(match.Success);
Assert.Equal("the", match.Groups[1].Value);
Assert.Equal(22, match.Groups[1].Index);
Assert.Equal(26, match.Groups[2].Index);
Assert.False(match.NextMatch().Success);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions#named-matched-subexpressions
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_GroupingConstructs_NamedMatchedSubexpression1(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// subcaptures not supported
return;
}
const string Pattern = @"(?<duplicateWord>\w+)\s\k<duplicateWord>\W(?<nextWord>\w+)";
const string Input = "He said that that was the the correct answer.";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern, RegexOptions.IgnoreCase);
Match match = r.Match(Input);
Assert.True(match.Success);
Assert.Equal("that", match.Groups["duplicateWord"].Value);
Assert.Equal(8, match.Groups["duplicateWord"].Index);
Assert.Equal("was", match.Groups["nextWord"].Value);
match = match.NextMatch();
Assert.True(match.Success);
Assert.Equal("the", match.Groups["duplicateWord"].Value);
Assert.Equal(22, match.Groups["duplicateWord"].Index);
Assert.Equal("correct", match.Groups["nextWord"].Value);
Assert.False(match.NextMatch().Success);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions#named-matched-subexpressions
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_GroupingConstructs_NamedMatchedSubexpression2(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// subcaptures not supported
return;
}
const string Pattern = @"\D+(?<digit>\d+)\D+(?<digit>\d+)?";
string[] inputs = { "abc123def456", "abc123def" };
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern);
var actual = new StringBuilder();
foreach (string input in inputs)
{
Match m = r.Match(input);
if (m.Success)
{
actual.AppendLine($"Match: {m.Value}");
for (int grpCtr = 1; grpCtr < m.Groups.Count; grpCtr++)
{
Group grp = m.Groups[grpCtr];
actual.AppendLine($"Group {grpCtr}: {grp.Value}");
for (int capCtr = 0; capCtr < grp.Captures.Count; capCtr++)
{
actual.AppendLine($" Capture {capCtr}: {grp.Captures[capCtr].Value}");
}
}
}
}
string expected =
"Match: abc123def456" + Environment.NewLine +
"Group 1: 456" + Environment.NewLine +
" Capture 0: 123" + Environment.NewLine +
" Capture 1: 456" + Environment.NewLine +
"Match: abc123def" + Environment.NewLine +
"Group 1: 123" + Environment.NewLine +
" Capture 0: 123" + Environment.NewLine;
Assert.Equal(expected, actual.ToString());
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions#balancing-group-definitions
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_GroupingConstructs_BalancingGroups(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// balancing groups not supported
return;
}
const string Pattern =
"^[^<>]*" +
"(" +
"((?'Open'<)[^<>]*)+" +
"((?'Close-Open'>)[^<>]*)+" +
")*" +
"(?(Open)(?!))$";
const string Input = "<abc><mno<xyz>>";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern);
var actual = new StringBuilder();
Match m = r.Match(Input);
if (m.Success)
{
actual.AppendLine($"Input: \"{Input}\"");
actual.AppendLine($"Match: \"{m}\"");
int grpCtr = 0;
foreach (Group grp in m.Groups)
{
actual.AppendLine($" Group {grpCtr}: {grp.Value}");
grpCtr++;
int capCtr = 0;
foreach (Capture cap in grp.Captures)
{
actual.AppendLine($" Capture {capCtr}: {cap.Value}");
capCtr++;
}
}
}
string expected =
"Input: \"<abc><mno<xyz>>\"" + Environment.NewLine +
"Match: \"<abc><mno<xyz>>\"" + Environment.NewLine +
" Group 0: <abc><mno<xyz>>" + Environment.NewLine +
" Capture 0: <abc><mno<xyz>>" + Environment.NewLine +
" Group 1: <mno<xyz>>" + Environment.NewLine +
" Capture 0: <abc>" + Environment.NewLine +
" Capture 1: <mno<xyz>>" + Environment.NewLine +
" Group 2: <xyz" + Environment.NewLine +
" Capture 0: <abc" + Environment.NewLine +
" Capture 1: <mno" + Environment.NewLine +
" Capture 2: <xyz" + Environment.NewLine +
" Group 3: >" + Environment.NewLine +
" Capture 0: >" + Environment.NewLine +
" Capture 1: >" + Environment.NewLine +
" Capture 2: >" + Environment.NewLine +
" Group 4: " + Environment.NewLine +
" Group 5: mno<xyz>" + Environment.NewLine +
" Capture 0: abc" + Environment.NewLine +
" Capture 1: xyz" + Environment.NewLine +
" Capture 2: mno<xyz>" + Environment.NewLine;
Assert.Equal(expected, actual.ToString());
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions#noncapturing-groups
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_GroupingConstructs_NoncapturingGroups(RegexEngine engine)
{
const string Pattern = @"(?:\b(?:\w+)\W*)+\.";
const string Input = "This is a short sentence.";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern);
Match match = r.Match(Input);
Assert.True(match.Success);
Assert.Equal("This is a short sentence.", match.Value);
Assert.Equal(1, match.Groups.Count);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions#group-options
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_GroupingConstructs_GroupOptions(RegexEngine engine)
{
const string Pattern = @"\b(?ix: d \w+)\s";
const string Input = "Dogs are decidedly good pets.";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern);
Match match = r.Match(Input);
Assert.True(match.Success);
Assert.Equal("Dogs ", match.Value);
Assert.Equal(0, match.Index);
match = match.NextMatch();
Assert.True(match.Success);
Assert.Equal("decidedly ", match.Value);
Assert.Equal(9, match.Index);
Assert.False(match.NextMatch().Success);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions#zero-width-positive-lookahead-assertions
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_GroupingConstructs_ZeroWidthPositiveLookaheadAssertions(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// lookaheads not supported
return;
}
const string Pattern = @"\b\w+(?=\sis\b)";
Match match;
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern);
match = r.Match("The dog is a Malamute.");
Assert.True(match.Success);
Assert.Equal("dog", match.Value);
match = r.Match("The island has beautiful birds.");
Assert.False(match.Success);
match = r.Match("The pitch missed home plate.");
Assert.False(match.Success);
match = r.Match("Sunday is a weekend day.");
Assert.True(match.Success);
Assert.Equal("Sunday", match.Value);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions#zero-width-negative-lookahead-assertions
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_GroupingConstructs_ZeroWidthNegativeLookaheadAssertions(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// lookaheads not supported
return;
}
const string Pattern = @"\b(?!un)\w+\b";
const string Input = "unite one unethical ethics use untie ultimate";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern, RegexOptions.IgnoreCase);
MatchCollection matches = r.Matches(Input);
Assert.Equal("one", matches[0].Value);
Assert.Equal("ethics", matches[1].Value);
Assert.Equal("use", matches[2].Value);
Assert.Equal("ultimate", matches[3].Value);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions#zero-width-positive-lookbehind-assertions
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_GroupingConstructs_ZeroWidthPositiveLookbehindAssertions(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// lookbehinds not supported
return;
}
const string Pattern = @"(?<=\b20)\d{2}\b";
const string Input = "2010 1999 1861 2140 2009";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern, RegexOptions.IgnoreCase);
MatchCollection matches = r.Matches(Input);
Assert.Equal("10", matches[0].Value);
Assert.Equal("09", matches[1].Value);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions#zero-width-negative-lookbehind-assertions
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_GroupingConstructs_ZeroWidthNegativeLookbehindAssertions(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// lookbehinds not supported
return;
}
const string Pattern = @"(?<!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern);
Assert.Equal("February 1, 2010", r.Match("Monday February 1, 2010").Value);
Assert.Equal("February 3, 2010", r.Match("Wednesday February 3, 2010").Value);
Assert.False(r.IsMatch("Saturday February 6, 2010"));
Assert.False(r.IsMatch("Sunday February 7, 2010"));
Assert.Equal("February 8, 2010", r.Match("Monday, February 8, 2010").Value);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions#nonbacktracking-subexpressions
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_GroupingConstructs_NonbacktrackingSubexpressions(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// atomic groups not supported
return;
}
Regex rBack = await RegexHelpers.GetRegexAsync(engine, @"(\w)\1+.\b");
Regex rNoBack = await RegexHelpers.GetRegexAsync(engine, @"(?>(\w)\1+).\b");
Match back, noback;
back = rBack.Match("cccd.");
noback = rNoBack.Match("cccd.");
Assert.True(back.Success);
Assert.True(noback.Success);
Assert.Equal("cccd", back.Value);
Assert.Equal("cccd", noback.Value);
back = rBack.Match("aaad");
noback = rNoBack.Match("aaad");
Assert.True(back.Success);
Assert.True(noback.Success);
Assert.Equal("aaad", back.Value);
Assert.Equal("aaad", noback.Value);
back = rBack.Match("aaaa");
noback = rNoBack.Match("aaaa");
Assert.True(back.Success);
Assert.False(noback.Success);
Assert.Equal("aaaa", back.Value);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions#grouping-constructs-and-regular-expression-objects
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_GroupingConstructs_GroupCaptureRelationship(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// subcaptures not supported
return;
}
const string Pattern = @"(\b(\w+)\W+)+";
const string Input = "This is a short sentence.";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern);
Match match = r.Match(Input);
var actual = new StringBuilder();
actual.AppendLine($"Match: '{match.Value}'");
for (int ctr = 1; ctr < match.Groups.Count; ctr++)
{
actual.AppendLine($" Group {ctr}: '{match.Groups[ctr].Value}'");
int capCtr = 0;
foreach (Capture capture in match.Groups[ctr].Captures)
{
actual.AppendLine($" Capture {capCtr}: '{capture.Value}'");
capCtr++;
}
}
string expected =
"Match: 'This is a short sentence.'" + Environment.NewLine +
" Group 1: 'sentence.'" + Environment.NewLine +
" Capture 0: 'This '" + Environment.NewLine +
" Capture 1: 'is '" + Environment.NewLine +
" Capture 2: 'a '" + Environment.NewLine +
" Capture 3: 'short '" + Environment.NewLine +
" Capture 4: 'sentence.'" + Environment.NewLine +
" Group 2: 'sentence'" + Environment.NewLine +
" Capture 0: 'This'" + Environment.NewLine +
" Capture 1: 'is'" + Environment.NewLine +
" Capture 2: 'a'" + Environment.NewLine +
" Capture 3: 'short'" + Environment.NewLine +
" Capture 4: 'sentence'" + Environment.NewLine;
Assert.Equal(expected, actual.ToString());
}
// https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.capture?view=netcore-3.1#examples
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_Capture_Sentences(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// subcaptures not supported
return;
}
const string Pattern = @"((\w+)[\s.])+";
const string Input = "Yes. This dog is very friendly.";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern);
var actual = new StringBuilder();
foreach (Match match in r.Matches(Input))
{
actual.AppendLine($"Match: {match.Value}");
for (int groupCtr = 0; groupCtr < match.Groups.Count; groupCtr++)
{
Group group = match.Groups[groupCtr];
actual.AppendLine($" Group {groupCtr}: {group.Value}");
for (int captureCtr = 0; captureCtr < group.Captures.Count; captureCtr++)
{
actual.AppendLine($" Capture {captureCtr}: {group.Captures[captureCtr].Value}");
}
}
}
string expected =
"Match: Yes." + Environment.NewLine +
" Group 0: Yes." + Environment.NewLine +
" Capture 0: Yes." + Environment.NewLine +
" Group 1: Yes." + Environment.NewLine +
" Capture 0: Yes." + Environment.NewLine +
" Group 2: Yes" + Environment.NewLine +
" Capture 0: Yes" + Environment.NewLine +
"Match: This dog is very friendly." + Environment.NewLine +
" Group 0: This dog is very friendly." + Environment.NewLine +
" Capture 0: This dog is very friendly." + Environment.NewLine +
" Group 1: friendly." + Environment.NewLine +
" Capture 0: This " + Environment.NewLine +
" Capture 1: dog " + Environment.NewLine +
" Capture 2: is " + Environment.NewLine +
" Capture 3: very " + Environment.NewLine +
" Capture 4: friendly." + Environment.NewLine +
" Group 2: friendly" + Environment.NewLine +
" Capture 0: This" + Environment.NewLine +
" Capture 1: dog" + Environment.NewLine +
" Capture 2: is" + Environment.NewLine +
" Capture 3: very" + Environment.NewLine +
" Capture 4: friendly" + Environment.NewLine;
Assert.Equal(expected, actual.ToString());
}
// https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.capture.value?view=netcore-3.1
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_Capture_ProductNumber(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// subcaptures not supported
return;
}
const string Pattern = @"^([a-z]+)(\d+)?\.([a-z]+(\d)*)$";
string[] values = { "AC10", "Za203.CYM", "XYZ.CoA", "ABC.x170" };
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern, RegexOptions.IgnoreCase);
var actual = new StringBuilder();
foreach (var value in values)
{
Match m = r.Match(value);
if (m.Success)
{
actual.AppendLine($"Match: '{m.Value}'");
actual.AppendLine($" Number of Capturing Groups: {m.Groups.Count}");
for (int gCtr = 0; gCtr < m.Groups.Count; gCtr++)
{
Group group = m.Groups[gCtr];
actual.AppendLine($" Group {gCtr}: {(group.Value == "" ? "<empty>" : "'" + group.Value + "'")}");
actual.AppendLine($" Number of Captures: {group.Captures.Count}");
for (int cCtr = 0; cCtr < group.Captures.Count; cCtr++)
{
actual.AppendLine($" Capture {cCtr}: {group.Captures[cCtr].Value}");
}
}
}
else
{
actual.AppendLine($"No match for {value}: Match.Value is {(m.Value == String.Empty ? "<empty>" : m.Value)}");
}
}
string expected =
"No match for AC10: Match.Value is <empty>" + Environment.NewLine +
"Match: 'Za203.CYM'" + Environment.NewLine +
" Number of Capturing Groups: 5" + Environment.NewLine +
" Group 0: 'Za203.CYM'" + Environment.NewLine +
" Number of Captures: 1" + Environment.NewLine +
" Capture 0: Za203.CYM" + Environment.NewLine +
" Group 1: 'Za'" + Environment.NewLine +
" Number of Captures: 1" + Environment.NewLine +
" Capture 0: Za" + Environment.NewLine +
" Group 2: '203'" + Environment.NewLine +
" Number of Captures: 1" + Environment.NewLine +
" Capture 0: 203" + Environment.NewLine +
" Group 3: 'CYM'" + Environment.NewLine +
" Number of Captures: 1" + Environment.NewLine +
" Capture 0: CYM" + Environment.NewLine +
" Group 4: <empty>" + Environment.NewLine +
" Number of Captures: 0" + Environment.NewLine +
"Match: 'XYZ.CoA'" + Environment.NewLine +
" Number of Capturing Groups: 5" + Environment.NewLine +
" Group 0: 'XYZ.CoA'" + Environment.NewLine +
" Number of Captures: 1" + Environment.NewLine +
" Capture 0: XYZ.CoA" + Environment.NewLine +
" Group 1: 'XYZ'" + Environment.NewLine +
" Number of Captures: 1" + Environment.NewLine +
" Capture 0: XYZ" + Environment.NewLine +
" Group 2: <empty>" + Environment.NewLine +
" Number of Captures: 0" + Environment.NewLine +
" Group 3: 'CoA'" + Environment.NewLine +
" Number of Captures: 1" + Environment.NewLine +
" Capture 0: CoA" + Environment.NewLine +
" Group 4: <empty>" + Environment.NewLine +
" Number of Captures: 0" + Environment.NewLine +
"Match: 'ABC.x170'" + Environment.NewLine +
" Number of Capturing Groups: 5" + Environment.NewLine +
" Group 0: 'ABC.x170'" + Environment.NewLine +
" Number of Captures: 1" + Environment.NewLine +
" Capture 0: ABC.x170" + Environment.NewLine +
" Group 1: 'ABC'" + Environment.NewLine +
" Number of Captures: 1" + Environment.NewLine +
" Capture 0: ABC" + Environment.NewLine +
" Group 2: <empty>" + Environment.NewLine +
" Number of Captures: 0" + Environment.NewLine +
" Group 3: 'x170'" + Environment.NewLine +
" Number of Captures: 1" + Environment.NewLine +
" Capture 0: x170" + Environment.NewLine +
" Group 4: '0'" + Environment.NewLine +
" Number of Captures: 3" + Environment.NewLine +
" Capture 0: 1" + Environment.NewLine +
" Capture 1: 7" + Environment.NewLine +
" Capture 2: 0" + Environment.NewLine;
Assert.Equal(expected, actual.ToString());
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/backtracking-in-regular-expressions#linear-comparison-without-backtracking
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_Backtracking_LinearComparisonWithoutBacktracking(RegexEngine engine)
{
const string Pattern = @"e{2}\w\b";
const string Input = "needing a reed";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern);
MatchCollection matches = r.Matches(Input);
Assert.Equal(1, matches.Count);
Assert.Equal("eed", matches[0].Value);
Assert.Equal(11, matches[0].Index);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/backtracking-in-regular-expressions#backtracking-with-optional-quantifiers-or-alternation-constructs
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_Backtracking_WithOptionalQuantifiersOrAlternationConstructs(RegexEngine engine)
{
const string Pattern = ".*(es)";
const string Input = "Essential services are provided by regular expressions.";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern, RegexOptions.IgnoreCase);
Match m = r.Match(Input);
Assert.True(m.Success);
Assert.Equal("Essential services are provided by regular expres", m.Value);
Assert.Equal(0, m.Index);
if (!RegexHelpers.IsNonBacktracking(engine))
{
Assert.Equal(47, m.Groups[1].Index);
}
Assert.False(m.NextMatch().Success);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/backtracking-in-regular-expressions#nonbacktracking-subexpression
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/57891")] // takes too long due to backtracking
public async Task Docs_Backtracking_WithNestedOptionalQuantifiers_ExcessiveBacktracking(RegexEngine engine)
{
Regex r = await RegexHelpers.GetRegexAsync(engine, "^(([0-9a-fA-F]{1,4}:)*([0-9a-fA-F]{1,4}))*(::)$");
Assert.False(r.IsMatch("b51:4:1DB:9EE1:5:27d60:f44:D4:cd:E:5:0A5:4a:D24:41Ad:"));
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/backtracking-in-regular-expressions#nonbacktracking-subexpression
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_Backtracking_WithNestedOptionalQuantifiers_BacktrackingEliminated(RegexEngine engine)
{
const string Input = "b51:4:1DB:9EE1:5:27d60:f44:D4:cd:E:5:0A5:4a:D24:41Ad:";
Regex r = await RegexHelpers.GetRegexAsync(engine, engine == RegexEngine.NonBacktracking ?
"^(([0-9a-fA-F]{1,4}:)*([0-9a-fA-F]{1,4}))*(::)$" : // Using RegexOptions.NonBacktracking to avoid backtracking
"^((?>[0-9a-fA-F]{1,4}:)*(?>[0-9a-fA-F]{1,4}))*(::)$"); // Using atomic to avoid backtracking
Assert.False(r.IsMatch(Input));
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/backtracking-in-regular-expressions#lookbehind-assertions
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_Backtracking_LookbehindAssertions(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// lookbehinds not supported
return;
}
const string Input = "test@contoso.com";
Regex rPattern = await RegexHelpers.GetRegexAsync(engine, @"^[0-9A-Z]([-.\w]*[0-9A-Z])?@", RegexOptions.IgnoreCase);
Assert.True(rPattern.IsMatch(Input));
Regex rBehindPattern = await RegexHelpers.GetRegexAsync(engine, @"^[0-9A-Z][-.\w]*(?<=[0-9A-Z])@", RegexOptions.IgnoreCase);
Assert.True(rBehindPattern.IsMatch(Input));
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/backtracking-in-regular-expressions#lookahead-assertions
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/57891")] // takes too long due to backtracking
public async Task Docs_Backtracking_LookaheadAssertions_ExcessiveBacktracking(RegexEngine engine)
{
Regex r = await RegexHelpers.GetRegexAsync(engine, @"^(([A-Z]\w*)+\.)*[A-Z]\w*$", RegexOptions.IgnoreCase);
Assert.False(r.IsMatch("aaaaaaaaaaaaaaaaaaaaaa."));
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/backtracking-in-regular-expressions#lookahead-assertions
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_Backtracking_LookaheadAssertions_BacktrackingEliminated(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// lookaheads not supported
return;
}
Regex r = await RegexHelpers.GetRegexAsync(engine, @"^((?=[A-Z])\w+\.)*[A-Z]\w*$", RegexOptions.IgnoreCase);
Assert.False(r.IsMatch("aaaaaaaaaaaaaaaaaaaaaa."));
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/details-of-regular-expression-behavior#net-framework-engine-capabilities
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_EngineCapabilities_LazyQuantifiers(RegexEngine engine)
{
const string Input = "This sentence ends with the number 107325.";
Regex rGreedy = await RegexHelpers.GetRegexAsync(engine, @".+(\d+)\.");
Match match = rGreedy.Match(Input);
Assert.True(match.Success);
if (!RegexHelpers.IsNonBacktracking(engine))
{
Assert.Equal("5", match.Groups[1].Value);
}
Regex rLazy = await RegexHelpers.GetRegexAsync(engine, @".+?(\d+)\.");
match = rLazy.Match(Input);
Assert.True(match.Success);
if (!RegexHelpers.IsNonBacktracking(engine))
{
Assert.Equal("107325", match.Groups[1].Value);
}
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/details-of-regular-expression-behavior#net-framework-engine-capabilities
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_EngineCapabilities_PositiveLookahead(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// lookaheads not supported
return;
}
const string Pattern = @"\b[A-Z]+\b(?=\P{P})";
const string Input = "If so, what comes next?";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern, RegexOptions.IgnoreCase);
MatchCollection matches = r.Matches(Input);
Assert.Equal(3, matches.Count);
Assert.Equal("If", matches[0].Value);
Assert.Equal("what", matches[1].Value);
Assert.Equal("comes", matches[2].Value);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/details-of-regular-expression-behavior#net-framework-engine-capabilities
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_EngineCapabilities_NegativeLookahead(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// lookaheads not supported
return;
}
const string Pattern = @"\b(?!non)\w+\b";
const string Input = "Nonsense is not always non-functional.";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern, RegexOptions.IgnoreCase);
MatchCollection matches = r.Matches(Input);
Assert.Equal(4, matches.Count);
Assert.Equal("is", matches[0].Value);
Assert.Equal("not", matches[1].Value);
Assert.Equal("always", matches[2].Value);
Assert.Equal("functional", matches[3].Value);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/alternation-constructs-in-regular-expressions#conditional-matching-with-an-expression
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_EngineCapabilities_ConditionalEvaluation(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// conditionals not supported
return;
}
const string Pattern = @"\b(?(\d{2}-)\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b";
const string Input = "01-9999999 020-333333 777-88-9999";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern);
MatchCollection matches = r.Matches(Input);
Assert.Equal(2, matches.Count);
Assert.Equal("01-9999999", matches[0].Value);
Assert.Equal(0, matches[0].Index);
Assert.Equal("777-88-9999", matches[1].Value);
Assert.Equal(22, matches[1].Index);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/details-of-regular-expression-behavior#net-framework-engine-capabilities
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_EngineCapabilities_RightToLeftMatching(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// RightToLeft not supported
return;
}
const string GreedyPattern = @".+(\d+)\.";
const string Input = "This sentence ends with the number 107325.";
Regex rLTR = await RegexHelpers.GetRegexAsync(engine, GreedyPattern);
Regex rRTL = await RegexHelpers.GetRegexAsync(engine, GreedyPattern, RegexOptions.RightToLeft);
// Match from left-to-right using lazy quantifier .+?.
Match match = rLTR.Match(Input);
Assert.True(match.Success);
Assert.Equal("5", match.Groups[1].Value);
// Match from right-to-left using greedy quantifier .+.
match = rRTL.Match(Input);
Assert.True(match.Success);
Assert.Equal("107325", match.Groups[1].Value);
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/details-of-regular-expression-behavior#net-framework-engine-capabilities
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_EngineCapabilities_PositiveNegativeLookbehind(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// lookbehinds not supported
return;
}
const string Pattern = @"^[A-Z0-9]([-!#$%&'.*+/=?^`{}|~\w])*(?<=[A-Z0-9])$";
Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern, RegexOptions.IgnoreCase);
Assert.True(r.IsMatch("jack.sprat"));
Assert.False(r.IsMatch("dog#"));
Assert.True(r.IsMatch("dog#1"));
Assert.True(r.IsMatch("me.myself"));
Assert.False(r.IsMatch("me.myself!"));
}
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/miscellaneous-constructs-in-regular-expressions#inline-options
[Theory]
[MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))]
public async Task Docs_InlineOptions(RegexEngine engine)
{
if (RegexHelpers.IsNonBacktracking(engine))
{
// subcaptures not supported
return;
}
const string Input = "double dare double Double a Drooling dog The Dreaded Deep";