在Java 7中,Regex-replace-with-function-evaluation等价于什么? [英] What is the equivalent of Regex-replace-with-function-evaluation in Java 7?
问题描述
我正在寻找一种非常简单的方法来获得与以下JavaScript代码类似的东西。也就是说,对于每场比赛,我想调用某个转换函数并将结果用作重置值。
var res =Hello World!。replace(/ \ S + /,function(word){
//由于这个函数表示一个转换,
//替换文字字符串(与replaceAll一样)不是可行的解决方案。
return+ word.length;
})
// res => 5 6
只有..在Java中。并且,最好作为可以重复使用的单一方法或模板。 解决方案
你的答案在 Matcher#appendReplacement 文档。只需将你的函数调用放在while循环中即可。
[appendReplacement方法]旨在与appendTail一起用于循环,找到方法。例如,下面的代码在标准输出流中写入一条狗两只狗:
Pattern p = Pattern.compile(cat);
Matcher m = p.matcher(院内一只猫两只猫);
StringBuffer sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb,dog);
}
m.appendTail(sb);
System.out.println(sb.toString());
I'm looking for a very simple way of getting the equivalent of something like the following JavaScript code. That is, for each match I would like to call a certain transformation function and use the result as the replacement value.
var res = "Hello World!".replace(/\S+/, function (word) {
// Since this function represents a transformation,
// replacing literal strings (as with replaceAll) are not a viable solution.
return "" + word.length;
})
// res => "5 6"
Only .. in Java. And, preferably as a "single method" or "template" that can be reused.
Your answer is in the Matcher#appendReplacement documentation. Just put your function call in the while loop.
[The appendReplacement method] is intended to be used in a loop together with the appendTail and find methods. The following code, for example, writes one dog two dogs in the yard to the standard-output stream:
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
这篇关于在Java 7中,Regex-replace-with-function-evaluation等价于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!