【发布时间】:2010-11-19 14:45:09
【问题描述】:
有没有办法用捕获组的修改内容替换正则表达式?
例子:
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher(text);
resultString = regexMatcher.replaceAll("$1"); // *3 ??
我想用 $1 乘以 3 替换所有出现的事件。
编辑:
好像出了点问题:(
如果我使用
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher("12 54 1 65");
try {
String resultString = regexMatcher.replaceAll(regexMatcher.group(1));
} catch (Exception e) {
e.printStackTrace();
}
它抛出一个 IllegalStateException: No match found
但是
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher("12 54 1 65");
try {
String resultString = regexMatcher.replaceAll("$1");
} catch (Exception e) {
e.printStackTrace();
}
工作正常,但我无法更改 $1 :(
编辑:
现在,它正在工作:)
【问题讨论】:
-
通过直接处理字符串,我们终于有了this