2 // System.IO.SearchPattern.cs: Filename glob support.
\r
5 // Dan Lewis (dihlewis@yahoo.co.uk)
\r
12 namespace System.IO {
\r
14 // FIXME: there's a complication with this algorithm under windows.
\r
15 // the pattern '*.*' matches all files (i think . matches the extension),
\r
16 // whereas under UNIX it should only match files containing the '.' character.
\r
18 class SearchPattern {
\r
19 public SearchPattern (string pattern) : this (pattern, false) { }
\r
21 public SearchPattern (string pattern, bool ignore)
\r
23 this.ignore = ignore;
\r
27 public bool IsMatch (string text)
\r
29 return Match (ops, text, 0);
\r
34 private Op ops; // the compiled pattern
\r
35 private bool ignore; // ignore case
\r
37 private void Compile (string pattern)
\r
39 if (pattern == null || pattern.IndexOfAny (InvalidChars) >= 0)
\r
40 throw new ArgumentException ("Invalid search pattern.");
\r
42 if (pattern == "*") { // common case
\r
43 ops = new Op (OpCode.True);
\r
51 while (ptr < pattern.Length) {
\r
54 switch (pattern [ptr]) {
\r
56 op = new Op (OpCode.AnyChar);
\r
61 op = new Op (OpCode.AnyString);
\r
66 op = new Op (OpCode.ExactString);
\r
67 int end = pattern.IndexOfAny (WildcardChars, ptr);
\r
69 end = pattern.Length;
\r
71 op.Argument = pattern.Substring (ptr, end - ptr);
\r
73 op.Argument = op.Argument.ToLower ();
\r
79 if (last_op == null)
\r
87 if (last_op == null)
\r
88 ops = new Op (OpCode.End);
\r
90 last_op.Next = new Op (OpCode.End);
\r
93 private bool Match (Op op, string text, int ptr)
\r
95 while (op != null) {
\r
101 if (ptr == text.Length)
\r
106 case OpCode.ExactString:
\r
107 int length = op.Argument.Length;
\r
108 if (ptr + length > text.Length)
\r
111 string str = text.Substring (ptr, length);
\r
113 str = str.ToLower ();
\r
115 if (str != op.Argument)
\r
121 case OpCode.AnyChar:
\r
122 if (++ ptr > text.Length)
\r
126 case OpCode.AnyString:
\r
127 while (ptr <= text.Length) {
\r
128 if (Match (op.Next, text, ptr))
\r
145 private static readonly char [] WildcardChars = { '*', '?' };
\r
146 private static readonly char [] InvalidChars = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
\r
149 public Op (OpCode code)
\r
152 this.Argument = null;
\r
156 public OpCode Code;
\r
157 public string Argument;
\r
161 private enum OpCode {
\r
162 ExactString, // literal
\r
165 End, // end of pattern
\r
166 True // always succeeds
\r