OLD | NEW |
| (Empty) |
1 // Copyright 2013 Google Inc. All Rights Reserved. | |
2 // | |
3 // Licensed under the Apache License, Version 2.0 (the "License"); | |
4 // you may not use this file except in compliance with the License. | |
5 // You may obtain a copy of the License at | |
6 // | |
7 // http://www.apache.org/licenses/LICENSE-2.0 | |
8 // | |
9 // Unless required by applicable law or agreed to in writing, software | |
10 // distributed under the License is distributed on an "AS IS" BASIS, | |
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
12 // See the License for the specific language governing permissions and | |
13 // limitations under the License. | |
14 | |
15 part of quiver.pattern; | |
16 | |
17 // TODO(justin): add more detailed documentation and explain how matching | |
18 // differs or is similar to globs in Python and various shells. | |
19 /** | |
20 * A [Pattern] that matches against filesystem path-like strings with | |
21 * wildcards. | |
22 * | |
23 * The pattern matches strings as follows: | |
24 * * The whole string must match, not a substring | |
25 * * Any non wildcard is matched as a literal | |
26 * * '*' matches one or more characters except '/' | |
27 * * '?' matches exactly one character except '/' | |
28 * * '**' matches one or more characters including '/' | |
29 */ | |
30 class Glob implements Pattern { | |
31 final RegExp regex; | |
32 final String pattern; | |
33 | |
34 Glob(String pattern) | |
35 : pattern = pattern, | |
36 regex = _regexpFromGlobPattern(pattern); | |
37 | |
38 Iterable<Match> allMatches(String str, [int start = 0]) => | |
39 regex.allMatches(str, start); | |
40 | |
41 Match matchAsPrefix(String string, [int start = 0]) => | |
42 regex.matchAsPrefix(string, start); | |
43 | |
44 bool hasMatch(String str) => regex.hasMatch(str); | |
45 | |
46 String toString() => pattern; | |
47 | |
48 int get hashCode => pattern.hashCode; | |
49 | |
50 bool operator ==(other) => other is Glob && pattern == other.pattern; | |
51 } | |
52 | |
53 RegExp _regexpFromGlobPattern(String pattern) { | |
54 var sb = new StringBuffer(); | |
55 sb.write('^'); | |
56 var chars = pattern.split(''); | |
57 for (var i = 0; i < chars.length; i++) { | |
58 var c = chars[i]; | |
59 if (_specialChars.hasMatch(c)) { | |
60 sb.write('\\$c'); | |
61 } else if (c == '*') { | |
62 if ((i + 1 < chars.length) && (chars[i + 1] == '*')) { | |
63 sb.write('.*'); | |
64 i++; | |
65 } else { | |
66 sb.write('[^/]*'); | |
67 } | |
68 } else if (c == '?') { | |
69 sb.write('[^/]'); | |
70 } else { | |
71 sb.write(c); | |
72 } | |
73 } | |
74 sb.write(r'$'); | |
75 return new RegExp(sb.toString()); | |
76 } | |
OLD | NEW |