forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathregex.cs
More file actions
1384 lines (1195 loc) · 51.2 KB
/
regex.cs
File metadata and controls
1384 lines (1195 loc) · 51.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
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma warning disable 1634, 1691
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Management.Automation.Internal;
using System.Runtime.Serialization;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// Provides enumerated values to use to set wildcard pattern
/// matching options.
/// </summary>
[Flags]
public enum WildcardOptions
{
/// <summary>
/// Indicates that no special processing is required.
/// </summary>
None = 0,
/// <summary>
/// Specifies that the wildcard pattern is compiled to an assembly.
/// This yields faster execution but increases startup time.
/// </summary>
Compiled = 1,
/// <summary>
/// Specifies case-insensitive matching.
/// </summary>
IgnoreCase = 2,
/// <summary>
/// Specifies culture-invariant matching.
/// </summary>
CultureInvariant = 4
}
/// <summary>
/// Represents a wildcard pattern.
/// </summary>
public sealed class WildcardPattern
{
// char that escapes special chars
private const char escapeChar = '`';
// Threshold for stack allocation.
// The size is less than MaxShortPath = 260.
private const int StackAllocThreshold = 256;
// chars that are considered special in a wildcard pattern
private const string SpecialChars = "*?[]`";
// we convert a wildcard pattern to a predicate
private Predicate<string> _isMatch;
// static match-all delegate that is shared by all WildcardPattern instances
private static readonly Predicate<string> s_matchAll = _ => true;
// wildcard pattern
internal string Pattern { get; }
// Options that control match behavior.
// Default is WildcardOptions.None.
internal WildcardOptions Options { get; }
/// <summary>
/// Wildcard pattern converted to regex pattern.
/// </summary>
internal string PatternConvertedToRegex
{
get
{
var patternRegex = WildcardPatternToRegexParser.Parse(this);
return patternRegex.ToString();
}
}
/// <summary>
/// Initializes and instance of the WildcardPattern class
/// for the specified wildcard pattern.
/// </summary>
/// <param name="pattern">The wildcard pattern to match.</param>
/// <returns>The constructed WildcardPattern object.</returns>
public WildcardPattern(string pattern) : this(pattern, WildcardOptions.None)
{
}
/// <summary>
/// Initializes an instance of the WildcardPattern class for
/// the specified wildcard pattern expression, with options
/// that modify the pattern.
/// </summary>
/// <param name="pattern">The wildcard pattern to match.</param>
/// <param name="options">Wildcard options.</param>
/// <returns>The constructed WildcardPattern object.</returns>
public WildcardPattern(string pattern, WildcardOptions options)
{
if (pattern == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(pattern));
}
Pattern = pattern;
Options = options;
}
private static readonly WildcardPattern s_matchAllIgnoreCasePattern = new WildcardPattern("*", WildcardOptions.None);
/// <summary>
/// Create a new WildcardPattern, or return an already created one.
/// </summary>
/// <param name="pattern">The pattern.</param>
/// <param name="options"></param>
/// <returns></returns>
public static WildcardPattern Get(string pattern, WildcardOptions options)
{
if (pattern == null)
throw PSTraceSource.NewArgumentNullException(nameof(pattern));
if (pattern.Length == 1 && pattern[0] == '*')
return s_matchAllIgnoreCasePattern;
return new WildcardPattern(pattern, options);
}
/// <summary>
/// Instantiate internal regex member if not already done.
/// </summary>
/// <returns>True on success, false otherwise.</returns>
private void Init()
{
StringComparison GetStringComparison()
{
StringComparison stringComparison;
if (Options.HasFlag(WildcardOptions.IgnoreCase))
{
stringComparison = Options.HasFlag(WildcardOptions.CultureInvariant)
? StringComparison.InvariantCultureIgnoreCase
: CultureInfo.CurrentCulture.Name.Equals("en-US-POSIX", StringComparison.OrdinalIgnoreCase)
// The collation behavior of the POSIX locale (also known as the C locale) is case sensitive.
// For this specific locale, we use 'OrdinalIgnoreCase'.
? StringComparison.OrdinalIgnoreCase
: StringComparison.CurrentCultureIgnoreCase;
}
else
{
stringComparison = Options.HasFlag(WildcardOptions.CultureInvariant)
? StringComparison.InvariantCulture
: StringComparison.CurrentCulture;
}
return stringComparison;
}
if (_isMatch != null)
{
return;
}
if (Pattern.Length == 1 && Pattern[0] == '*')
{
_isMatch = s_matchAll;
return;
}
int index = Pattern.AsSpan().IndexOfAny(SpecialChars);
if (index < 0)
{
// No special characters present in the pattern, so we can just do a string comparison.
_isMatch = str => string.Equals(str, Pattern, GetStringComparison());
return;
}
if (index == Pattern.Length - 1 && Pattern[index] == '*')
{
// No special characters present in the pattern before last position and last character is asterisk.
var patternWithoutAsterisk = Pattern.AsMemory(0, index);
_isMatch = str => str.AsSpan().StartsWith(patternWithoutAsterisk.Span, GetStringComparison());
return;
}
var matcher = new WildcardPatternMatcher(this);
_isMatch = matcher.IsMatch;
}
/// <summary>
/// Indicates whether the wildcard pattern specified in the WildcardPattern
/// constructor finds a match in the input string.
/// </summary>
/// <param name="input">The string to search for a match.</param>
/// <returns>True if the wildcard pattern finds a match; otherwise, false.</returns>
public bool IsMatch(string input)
{
Init();
return input != null && _isMatch(input);
}
/// <summary>
/// Escape special chars, except for those specified in <paramref name="charsNotToEscape"/>, in a string by replacing them with their escape codes.
/// </summary>
/// <param name="pattern">The input string containing the text to convert.</param>
/// <param name="charsNotToEscape">Array of characters that not to escape.</param>
/// <returns>
/// A string of characters with any metacharacters, except for those specified in <paramref name="charsNotToEscape"/>, converted to their escaped form.
/// </returns>
internal static string Escape(string pattern, char[] charsNotToEscape)
{
if (pattern == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(pattern));
}
if (charsNotToEscape == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(charsNotToEscape));
}
if (pattern == string.Empty)
{
return pattern;
}
Span<char> temp = pattern.Length < StackAllocThreshold ? stackalloc char[pattern.Length * 2 + 1] : new char[pattern.Length * 2 + 1];
int tempIndex = 0;
for (int i = 0; i < pattern.Length; i++)
{
char ch = pattern[i];
//
// if it is a special char, escape it
//
if (SpecialChars.Contains(ch) && !charsNotToEscape.Contains(ch))
{
temp[tempIndex++] = escapeChar;
}
temp[tempIndex++] = ch;
}
string s = null;
if (tempIndex == pattern.Length)
{
s = pattern;
}
else
{
s = new string(temp.Slice(0, tempIndex));
}
return s;
}
/// <summary>
/// Escape special chars in a string by replacing them with their escape codes.
/// </summary>
/// <param name="pattern">The input string containing the text to convert.</param>
/// <returns>
/// A string of characters with any metacharacters converted to their escaped form.
/// </returns>
public static string Escape(string pattern)
{
return Escape(pattern, Array.Empty<char>());
}
/// <summary>
/// Checks to see if the given string has any wild card characters in it.
/// </summary>
/// <param name="pattern">
/// String which needs to be checked for the presence of wildcard chars
/// </param>
/// <returns>True if the string has wild card chars, false otherwise..</returns>
/// <remarks>
/// Currently { '*', '?', '[' } are considered wild card chars and
/// '`' is the escape character.
/// </remarks>
public static bool ContainsWildcardCharacters(string pattern)
{
if (string.IsNullOrEmpty(pattern))
{
return false;
}
bool result = false;
for (int index = 0; index < pattern.Length; ++index)
{
if (IsWildcardChar(pattern[index]))
{
result = true;
break;
}
// If it is an escape character then advance past
// the next character
if (pattern[index] == escapeChar)
{
++index;
}
}
return result;
}
/// <summary>
/// Checks if the string contains a left bracket "[" followed by a right bracket "]" after any number of characters.
/// </summary>
/// <param name="pattern"> The string to check.</param>
/// <returns>Returns true if the string contains both a left and right bracket "[" "]" and if the right bracket comes after the left bracket.</returns>
internal static bool ContainsRangeWildcard(string pattern)
{
if (string.IsNullOrEmpty(pattern))
{
return false;
}
bool foundStart = false;
bool result = false;
for (int index = 0; index < pattern.Length; ++index)
{
if (pattern[index] is '[')
{
foundStart = true;
continue;
}
if (foundStart && pattern[index] is ']')
{
result = true;
break;
}
if (pattern[index] == escapeChar)
{
++index;
}
}
return result;
}
/// <summary>
/// Unescapes any escaped characters in the input string.
/// </summary>
/// <param name="pattern">
/// The input string containing the text to convert.
/// </param>
/// <returns>
/// A string of characters with any escaped characters
/// converted to their unescaped form.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="pattern"/> is null.
/// </exception>
public static string Unescape(string pattern)
{
if (pattern == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(pattern));
}
if (pattern == string.Empty)
{
return pattern;
}
Span<char> temp = pattern.Length < StackAllocThreshold ? stackalloc char[pattern.Length] : new char[pattern.Length];
int tempIndex = 0;
bool prevCharWasEscapeChar = false;
for (int i = 0; i < pattern.Length; i++)
{
char ch = pattern[i];
if (ch == escapeChar)
{
if (prevCharWasEscapeChar)
{
temp[tempIndex++] = ch;
prevCharWasEscapeChar = false;
}
else
{
prevCharWasEscapeChar = true;
}
continue;
}
if (prevCharWasEscapeChar)
{
if (!IsWildcardChar(ch))
{
temp[tempIndex++] = escapeChar;
}
}
temp[tempIndex++] = ch;
prevCharWasEscapeChar = false;
}
// Need to account for a trailing escape character as a real
// character
if (prevCharWasEscapeChar)
{
temp[tempIndex++] = escapeChar;
prevCharWasEscapeChar = false;
}
string s = null;
if (tempIndex == pattern.Length)
{
s = pattern;
}
else
{
s = new string(temp.Slice(0, tempIndex));
}
return s;
}
private static bool IsWildcardChar(char ch)
{
return (ch == '*') || (ch == '?') || (ch == '[') || (ch == ']');
}
/// <summary>
/// Converts this wildcard to a string that can be used as a right-hand-side operand of the LIKE operator of WQL.
/// For example: "a*" will be converted to "a%".
/// </summary>
/// <returns></returns>
public string ToWql()
{
bool needsClientSideFiltering;
string likeOperand = Microsoft.PowerShell.Cmdletization.Cim.WildcardPatternToCimQueryParser.Parse(this, out needsClientSideFiltering);
if (!needsClientSideFiltering)
{
return likeOperand;
}
else
{
throw new PSInvalidCastException(
"UnsupportedWildcardToWqlConversion",
null,
ExtendedTypeSystem.InvalidCastException,
this.Pattern,
this.GetType().FullName,
"WQL");
}
}
}
/// <summary>
/// Thrown when a wildcard pattern is invalid.
/// </summary>
public class WildcardPatternException : RuntimeException
{
/// <summary>
/// Constructor for class WildcardPatternException that takes
/// an ErrorRecord to use in constructing this exception.
/// </summary>
/// <remarks>This is the recommended constructor to use for this exception.</remarks>
/// <param name="errorRecord">
/// ErrorRecord object containing additional information about the error condition.
/// </param>
/// <returns>Constructed object.</returns>
internal WildcardPatternException(ErrorRecord errorRecord)
: base(RetrieveMessage(errorRecord))
{
ArgumentNullException.ThrowIfNull(errorRecord);
_errorRecord = errorRecord;
}
[NonSerialized]
private readonly ErrorRecord _errorRecord;
/// <summary>
/// Constructs an instance of the WildcardPatternException object.
/// </summary>
public WildcardPatternException()
{
}
/// <summary>
/// Constructs an instance of the WildcardPatternException object taking
/// a message parameter to use in constructing the exception.
/// </summary>
/// <param name="message">The string to use as the exception message.</param>
public WildcardPatternException(string message) : base(message)
{
}
/// <summary>
/// Constructor for class WildcardPatternException that takes both a message to use
/// and an inner exception to include in this object.
/// </summary>
/// <param name="message">The exception message to use.</param>
/// <param name="innerException">The innerException object to encapsulate.</param>
public WildcardPatternException(string message,
Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Constructor for class WildcardPatternException for serialization.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
[Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")]
protected WildcardPatternException(SerializationInfo info,
StreamingContext context)
{
throw new NotSupportedException();
}
}
/// <summary>
/// A base class for parsers of <see cref="WildcardPattern"/> patterns.
/// </summary>
internal abstract class WildcardPatternParser
{
/// <summary>
/// Called from <see cref="Parse"/> method to indicate
/// the beginning of the wildcard pattern.
/// Default implementation simply returns.
/// </summary>
/// <param name="pattern">
/// <see cref="WildcardPattern"/> object that includes both
/// the text of the pattern (<see cref="WildcardPattern.Pattern"/>)
/// and the pattern options (<see cref="WildcardPattern.Options"/>)
/// </param>
protected virtual void BeginWildcardPattern(WildcardPattern pattern)
{
}
/// <summary>
/// Called from <see cref="Parse"/> method to indicate that the next
/// part of the pattern should match
/// a literal character <paramref name="c"/>.
/// </summary>
protected abstract void AppendLiteralCharacter(char c);
/// <summary>
/// Called from <see cref="Parse"/> method to indicate that the next
/// part of the pattern should match
/// any string, including an empty string.
/// </summary>
protected abstract void AppendAsterix();
/// <summary>
/// Called from <see cref="Parse"/> method to indicate that the next
/// part of the pattern should match
/// any single character.
/// </summary>
protected abstract void AppendQuestionMark();
/// <summary>
/// Called from <see cref="Parse"/> method to indicate the end of the wildcard pattern.
/// Default implementation simply returns.
/// </summary>
protected virtual void EndWildcardPattern()
{
}
/// <summary>
/// Called from <see cref="Parse"/> method to indicate
/// the beginning of a bracket expression.
/// </summary>
/// <remarks>
/// Bracket expressions of <see cref="WildcardPattern"/> are
/// a greatly simplified version of bracket expressions of POSIX wildcards
/// (https://www.opengroup.org/onlinepubs/9699919799/functions/fnmatch.html).
/// Only literal characters and character ranges are supported.
/// Negation (with either '!' or '^' characters),
/// character classes ([:alpha:])
/// and other advanced features are not supported.
/// </remarks>
protected abstract void BeginBracketExpression();
/// <summary>
/// Called from <see cref="Parse"/> method to indicate that the bracket expression
/// should include a literal character <paramref name="c"/>.
/// </summary>
protected abstract void AppendLiteralCharacterToBracketExpression(char c);
/// <summary>
/// Called from <see cref="Parse"/> method to indicate that the bracket expression
/// should include all characters from character range
/// starting at <paramref name="startOfCharacterRange"/>
/// and ending at <paramref name="endOfCharacterRange"/>
/// </summary>
protected abstract void AppendCharacterRangeToBracketExpression(
char startOfCharacterRange,
char endOfCharacterRange);
/// <summary>
/// Called from <see cref="Parse"/> method to indicate the end of a bracket expression.
/// </summary>
protected abstract void EndBracketExpression();
/// <summary>
/// PowerShell v1 and v2 treats all characters inside
/// <paramref name="brackedExpressionContents"/> as literal characters,
/// except '-' sign which denotes a range. In particular it means that
/// '^', '[', ']' are escaped within the bracket expression and don't
/// have their regex-y meaning.
/// </summary>
/// <param name="brackedExpressionContents"></param>
/// <param name="bracketExpressionOperators"></param>
/// <param name="pattern"></param>
/// <remarks>
/// This method should be kept "internal"
/// </remarks>
internal void AppendBracketExpression(string brackedExpressionContents, string bracketExpressionOperators, string pattern)
{
this.BeginBracketExpression();
int i = 0;
while (i < brackedExpressionContents.Length)
{
if (((i + 2) < brackedExpressionContents.Length) &&
(bracketExpressionOperators[i + 1] == '-'))
{
char lowerBound = brackedExpressionContents[i];
char upperBound = brackedExpressionContents[i + 2];
i += 3;
if (lowerBound > upperBound)
{
throw NewWildcardPatternException(pattern);
}
this.AppendCharacterRangeToBracketExpression(lowerBound, upperBound);
}
else
{
this.AppendLiteralCharacterToBracketExpression(brackedExpressionContents[i]);
i++;
}
}
this.EndBracketExpression();
}
/// <summary>
/// Parses <paramref name="pattern"/>, calling appropriate overloads
/// in <paramref name="parser"/>
/// </summary>
/// <param name="pattern">Pattern to parse.</param>
/// <param name="parser">Parser to call back.</param>
public static void Parse(WildcardPattern pattern, WildcardPatternParser parser)
{
parser.BeginWildcardPattern(pattern);
bool previousCharacterIsAnEscape = false;
bool previousCharacterStartedBracketExpression = false;
bool insideCharacterRange = false;
StringBuilder characterRangeContents = null;
StringBuilder characterRangeOperators = null;
foreach (char c in pattern.Pattern)
{
if (insideCharacterRange)
{
if (c == ']' && !previousCharacterStartedBracketExpression && !previousCharacterIsAnEscape)
{
// An unescaped closing square bracket closes the character set. In other
// words, there are no nested square bracket expressions
// This is different than the POSIX spec
// (at https://www.opengroup.org/onlinepubs/9699919799/functions/fnmatch.html),
// but we are keeping this behavior for back-compatibility.
insideCharacterRange = false;
parser.AppendBracketExpression(characterRangeContents.ToString(), characterRangeOperators.ToString(), pattern.Pattern);
characterRangeContents = null;
characterRangeOperators = null;
}
else if (c != '`' || previousCharacterIsAnEscape)
{
characterRangeContents.Append(c);
characterRangeOperators.Append((c == '-') && !previousCharacterIsAnEscape ? '-' : ' ');
}
previousCharacterStartedBracketExpression = false;
}
else
{
if (c == '*' && !previousCharacterIsAnEscape)
{
parser.AppendAsterix();
}
else if (c == '?' && !previousCharacterIsAnEscape)
{
parser.AppendQuestionMark();
}
else if (c == '[' && !previousCharacterIsAnEscape)
{
insideCharacterRange = true;
characterRangeContents = new StringBuilder();
characterRangeOperators = new StringBuilder();
previousCharacterStartedBracketExpression = true;
}
else if (c != '`' || previousCharacterIsAnEscape)
{
parser.AppendLiteralCharacter(c);
}
}
previousCharacterIsAnEscape = (c == '`') && (!previousCharacterIsAnEscape);
}
if (insideCharacterRange)
{
throw NewWildcardPatternException(pattern.Pattern);
}
if (previousCharacterIsAnEscape)
{
if (!pattern.Pattern.Equals("`", StringComparison.Ordinal)) // Win7 backcompatibility requires treating '`' pattern as '' pattern
{
parser.AppendLiteralCharacter(pattern.Pattern[pattern.Pattern.Length - 1]);
}
}
parser.EndWildcardPattern();
}
internal static WildcardPatternException NewWildcardPatternException(string invalidPattern)
{
string message =
StringUtil.Format(WildcardPatternStrings.InvalidPattern,
invalidPattern
);
ParentContainsErrorRecordException pce =
new ParentContainsErrorRecordException(message);
ErrorRecord er =
new ErrorRecord(pce,
"WildcardPattern_Invalid",
ErrorCategory.InvalidArgument,
null);
WildcardPatternException e =
new WildcardPatternException(er);
return e;
}
}
/// <summary>
/// Convert a string with wild cards into its equivalent regex.
/// </summary>
/// <remarks>
/// A list of glob patterns and their equivalent regexes
///
/// glob pattern regex
/// ------------- -------
/// *foo* foo
/// foo ^foo$
/// foo*bar ^foo.*bar$
/// foo`*bar ^foo\*bar$
///
/// for a more cases see the unit-test file RegexTest.cs
/// </remarks>
internal class WildcardPatternToRegexParser : WildcardPatternParser
{
private StringBuilder _regexPattern;
private RegexOptions _regexOptions;
private const string regexChars = "()[.?*{}^$+|\\"; // ']' is missing on purpose
private static bool IsRegexChar(char ch)
{
for (int i = 0; i < regexChars.Length; i++)
{
if (ch == regexChars[i])
{
return true;
}
}
return false;
}
internal static RegexOptions TranslateWildcardOptionsIntoRegexOptions(WildcardOptions options)
{
RegexOptions regexOptions = RegexOptions.Singleline;
if ((options & WildcardOptions.Compiled) != 0)
{
regexOptions |= RegexOptions.Compiled;
}
if ((options & WildcardOptions.IgnoreCase) != 0)
{
regexOptions |= RegexOptions.IgnoreCase;
}
if ((options & WildcardOptions.CultureInvariant) == WildcardOptions.CultureInvariant)
{
regexOptions |= RegexOptions.CultureInvariant;
}
return regexOptions;
}
protected override void BeginWildcardPattern(WildcardPattern pattern)
{
_regexPattern = new StringBuilder(pattern.Pattern.Length * 2 + 2);
_regexPattern.Append('^');
_regexOptions = TranslateWildcardOptionsIntoRegexOptions(pattern.Options);
}
internal static void AppendLiteralCharacter(StringBuilder regexPattern, char c)
{
if (IsRegexChar(c))
{
regexPattern.Append('\\');
}
regexPattern.Append(c);
}
protected override void AppendLiteralCharacter(char c)
{
AppendLiteralCharacter(_regexPattern, c);
}
protected override void AppendAsterix()
{
_regexPattern.Append(".*");
}
protected override void AppendQuestionMark()
{
_regexPattern.Append('.');
}
protected override void EndWildcardPattern()
{
_regexPattern.Append('$');
// lines below are not strictly necessary and are included to preserve
// wildcard->regex conversion from PS v1 (i.e. not to break unit tests
// and not to break backcompatibility).
string regexPatternString = _regexPattern.ToString();
if (regexPatternString.Equals("^.*$", StringComparison.Ordinal))
{
_regexPattern.Remove(0, 4);
}
else
{
if (regexPatternString.StartsWith("^.*", StringComparison.Ordinal))
{
_regexPattern.Remove(0, 3);
}
if (regexPatternString.EndsWith(".*$", StringComparison.Ordinal))
{
_regexPattern.Remove(_regexPattern.Length - 3, 3);
}
}
}
protected override void BeginBracketExpression()
{
_regexPattern.Append('[');
}
internal static void AppendLiteralCharacterToBracketExpression(StringBuilder regexPattern, char c)
{
if (c == '[')
{
regexPattern.Append('[');
}
else if (c == ']')
{
regexPattern.Append(@"\]");
}
else if (c == '-')
{
regexPattern.Append(@"\x2d");
}
else
{
AppendLiteralCharacter(regexPattern, c);
}
}
protected override void AppendLiteralCharacterToBracketExpression(char c)
{
AppendLiteralCharacterToBracketExpression(_regexPattern, c);
}
internal static void AppendCharacterRangeToBracketExpression(
StringBuilder regexPattern,
char startOfCharacterRange,
char endOfCharacterRange)
{
AppendLiteralCharacterToBracketExpression(regexPattern, startOfCharacterRange);
regexPattern.Append('-');
AppendLiteralCharacterToBracketExpression(regexPattern, endOfCharacterRange);
}
protected override void AppendCharacterRangeToBracketExpression(
char startOfCharacterRange,
char endOfCharacterRange)
{
AppendCharacterRangeToBracketExpression(_regexPattern, startOfCharacterRange, endOfCharacterRange);
}
protected override void EndBracketExpression()
{
_regexPattern.Append(']');
}
/// <summary>
/// Parses a <paramref name="wildcardPattern"/> into a <see cref="Regex"/>
/// </summary>
/// <param name="wildcardPattern">Wildcard pattern to parse.</param>
/// <returns>Regular expression equivalent to <paramref name="wildcardPattern"/></returns>
public static Regex Parse(WildcardPattern wildcardPattern)
{
WildcardPatternToRegexParser parser = new WildcardPatternToRegexParser();
WildcardPatternParser.Parse(wildcardPattern, parser);
try
{
return ParserOps.NewRegex(parser._regexPattern.ToString(), parser._regexOptions);
}
catch (ArgumentException)
{
throw WildcardPatternParser.NewWildcardPatternException(wildcardPattern.Pattern);
}
}
}
internal class WildcardPatternMatcher
{
private readonly PatternElement[] _patternElements;
private readonly CharacterNormalizer _characterNormalizer;
internal WildcardPatternMatcher(WildcardPattern wildcardPattern)
{
_characterNormalizer = new CharacterNormalizer(wildcardPattern.Options);
_patternElements = MyWildcardPatternParser.Parse(
wildcardPattern,
_characterNormalizer);
}
internal bool IsMatch(string str)
{
// - each state of NFA is represented by (patternPosition, stringPosition) tuple
// - state transitions are documented in
// ProcessStringCharacter and ProcessEndOfString methods
// - the algorithm below tries to see if there is a path
// from (0, 0) to (lengthOfPattern, lengthOfString)
// - this is a regular graph traversal
// - there are O(1) edges per node (at most 2 edges)
// so the whole graph traversal takes O(number of nodes in the graph) =
// = O(lengthOfPattern * lengthOfString) time
// - for efficient remembering which states have already been visited,
// the traversal goes methodically from beginning to end of the string
// therefore requiring only O(lengthOfPattern) memory for remembering
// which states have been already visited
// - Wikipedia calls this algorithm the "NFA" algorithm at
// https://en.wikipedia.org/wiki/Regular_expression#Implementations_and_running_times
var patternPositionsForCurrentStringPosition =
new PatternPositionsVisitor(_patternElements.Length);
patternPositionsForCurrentStringPosition.Add(0);
var patternPositionsForNextStringPosition =
new PatternPositionsVisitor(_patternElements.Length);
try
{
for (int currentStringPosition = 0;
currentStringPosition < str.Length;
currentStringPosition++)
{
char currentStringCharacter = _characterNormalizer.Normalize(str[currentStringPosition]);