通常,当使用正则表达式时,我可以使用$运算符来引用捕获的组,如下所示:
value.replaceAll("([A-Z])", "$1");
Run Code Online (Sandbox Code Playgroud)
我想知道的是,是否有可能在方法调用中使用捕获的值,然后将组替换为方法的返回值,如下所示:
value.replaceAll("([A-Z])", foo("$1"));
Run Code Online (Sandbox Code Playgroud)
以上述方式进行操作不起作用,毫无疑问,传入的字符串不是捕获的组,而是string "$1"。
有什么方法可以将捕获的值用作某个方法的参数?能做到吗
是的,这是可能的,但是您不能$1正确使用该构造。
你最好的选择是使用Pattern与Matcher此。
这是一个示例说明:
import java.util.regex.*;
public class Test {
public static String foo(String str) {
return "<b>" + str + "</b>";
}
public static void main(String[] args) {
String content = "Some Text";
Pattern pattern = Pattern.compile("[A-Z]");
Matcher m = pattern.matcher(content);
StringBuffer sb = new StringBuffer();
while (m.find())
m.appendReplacement(sb, foo(m.group()));
m.appendTail(sb);
System.out.println(sb);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
<b>S</b>ome <b>T</b>ext
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1179 次 |
| 最近记录: |