-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathStringFinder.ts
44 lines (40 loc) · 1015 Bytes
/
StringFinder.ts
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
export default class StringFinder {
private newlinesRegex: RegExp;
constructor(needles: string[]|RegExp) {
if (needles instanceof RegExp) {
if (!needles.global) {
throw new Error('StringFinder regular expression must have a global flag');
}
this.newlinesRegex = <any>needles;
return;
}
if (needles instanceof Array) {
this.newlinesRegex = this.convertToPipedExpression(<any>needles);
return;
}
throw new Error('Unexpected type in StringFinder constructor argument: ' + typeof needles);
}
private convertToPipedExpression(needles: string[]) {
needles = needles.map(needle => {
return needle.replace('\\', '\\\\');
});
return new RegExp('(' + needles.join('|') + ')', 'g');
}
findAll(haystack: string) {
var matches: {
index: number;
text: string;
}[] = [];
while (true) {
var match = this.newlinesRegex.exec(haystack);
if (!match) {
break;
}
matches.push({
index: match.index,
text: match[0]
});
}
return matches;
}
}