feat(facade): add RegExpWrapper.replaceAll to replace all matches using the provided function
This commit is contained in:
parent
aa966f5de2
commit
91999e016e
@ -215,6 +215,20 @@ class RegExpWrapper {
|
|||||||
static Iterator<Match> matcher(RegExp regExp, String input) {
|
static Iterator<Match> matcher(RegExp regExp, String input) {
|
||||||
return regExp.allMatches(input).iterator;
|
return regExp.allMatches(input).iterator;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static String replaceAll(RegExp regExp, String input, Function replace) {
|
||||||
|
final m = RegExpWrapper.matcher(regExp, input);
|
||||||
|
var res = "";
|
||||||
|
var prev = 0;
|
||||||
|
while(m.moveNext()) {
|
||||||
|
var c = m.current;
|
||||||
|
res += input.substring(prev, c.start);
|
||||||
|
res += replace(c);
|
||||||
|
prev = c.start + c[0].length;
|
||||||
|
}
|
||||||
|
res += input.substring(prev);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class RegExpMatcherWrapper {
|
class RegExpMatcherWrapper {
|
||||||
|
@ -347,6 +347,21 @@ export class RegExpWrapper {
|
|||||||
regExp.lastIndex = 0;
|
regExp.lastIndex = 0;
|
||||||
return {re: regExp, input: input};
|
return {re: regExp, input: input};
|
||||||
}
|
}
|
||||||
|
static replaceAll(regExp: RegExp, input: string, replace: Function): string {
|
||||||
|
let c = regExp.exec(input);
|
||||||
|
let res = '';
|
||||||
|
regExp.lastIndex = 0;
|
||||||
|
let prev = 0;
|
||||||
|
while (c) {
|
||||||
|
res += input.substring(prev, c.index);
|
||||||
|
res += replace(c);
|
||||||
|
prev = c.index + c[0].length;
|
||||||
|
regExp.lastIndex = prev;
|
||||||
|
c = regExp.exec(input);
|
||||||
|
}
|
||||||
|
res += input.substring(prev);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class RegExpMatcherWrapper {
|
export class RegExpMatcherWrapper {
|
||||||
|
@ -42,6 +42,12 @@ export function main() {
|
|||||||
// If not reset, the second attempt to test results in false
|
// If not reset, the second attempt to test results in false
|
||||||
expect(RegExpWrapper.test(re, str)).toEqual(true);
|
expect(RegExpWrapper.test(re, str)).toEqual(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("should implement replace all", () => {
|
||||||
|
let re = /(\d)+/g;
|
||||||
|
let m = RegExpWrapper.replaceAll(re, 'a1b2c', (match) => `!${match[1]}!`);
|
||||||
|
expect(m).toEqual('a!1!b!2!c');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('const', () => {
|
describe('const', () => {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user