【发布时间】:2010-11-19 15:55:57
【问题描述】:
有没有办法用捕获组的修改内容替换正则表达式?
例子:
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 :(
edit2:
现在,它正在工作:)
【问题讨论】:
-
如果其他用户遇到类似问题,您能否详细说明您为纠正该问题所做的工作? :)
-
我不知道如何在 Java 中做到这一点,但在 Perl 中这很容易。 :-P $foo = '12 54 1 65'; $foo =~ s/(\d{1,2})/$1 * 3/eg;
-
这是一个描述如何做的答案,我不知道它现在在哪里......(我接受了一个解决问题的问题,但消失了。奇怪...... )
-
我认为 [this question][1] 的答案可以帮助您。 [1]:stackoverflow.com/questions/375420/…