以下 (Java) 实现是 GDK 的一部分:
/**
* Replaces all occurrences of a captured group by the result of a closure on that text.
* <p/>
* <p> For examples,
* <pre>
* assert "FOOBAR-FOOBAR-" == "foobar-FooBar-".replaceAll(~"(([fF][oO]{2})[bB]ar)", { Object[] it -> it[0].toUpperCase() })
* <p/>
* Here,
* it[0] is the global string of the matched group
* it[1] is the first string in the matched group
* it[2] is the second string in the matched group
* <p/>
* <p/>
* assert "FOO-FOO-" == "foobar-FooBar-".replaceAll("(([fF][oO]{2})[bB]ar)", { x, y, z -> z.toUpperCase() })
* <p/>
* Here,
* x is the global string of the matched group
* y is the first string in the matched group
* z is the second string in the matched group
* </pre>
* <p>Note that unlike String.replaceAll(String regex, String replacement), where the replacement string
* treats '$' and '\' specially (for group substitution), the result of the closure is converted to a string
* and that value is used literally for the replacement.</p>
*
* @param self a String
* @param pattern the capturing regex Pattern
* @param closure the closure to apply on each captured group
* @return a String with replaced content
* @since 1.6.8
* @see java.util.regex.Matcher#quoteReplacement(java.lang.String)
*/
public static String replaceAll(final String self, final Pattern pattern, final Closure closure) {
final Matcher matcher = pattern.matcher(self);
if (matcher.find()) {
final StringBuffer sb = new StringBuffer(self.length() + 16);
do {
int count = matcher.groupCount();
List<String> groups = new ArrayList<String>();
for (int i = 0; i <= count; i++) {
groups.add(matcher.group(i));
}
final String replacement = InvokerHelper.toString(closure.call(groups.toArray()));
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
} while (matcher.find());
matcher.appendTail(sb);
return sb.toString();
} else {
return self;
}
}
是否有任何类似的 Javascript 实现?如果不行,自己尝试实现是否可行?怎么办?
最佳答案
我希望我能正确理解您的问题,但是阅读您示例中的注释,示例用例可以通过 js String 对象的 replace
方法来满足。 replace
可以将函数作为其替换参数:
// true
console.log(
"FOOBAR-FOOBAR-" == "foobar-FooBar-".replace(
/(([fF][oO]{2})[bB]ar)/g,
function( all, capture1, capture2 ) {
return all.toUpperCase();
}
)
);
// true
console.log(
"FOO-FOO-" == "foobar-FooBar-".replace(
/(([fF][oO]{2})[bB]ar)/g,
function( all, capture1, capture2 ) {
return capture2.toUpperCase();
}
)
);
关于java - 任何 Javascript Regex ReplaceAll 都像 Groovy 一样由匿名函数实现吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4608067/