Java 正则表达式替换为捕获组 [英] Java Regex Replace with Capturing Group
问题描述
有没有办法用捕获组的修改内容替换正则表达式?
Is there any way to replace a regexp with modified content of capture group?
示例:
Pattern regex = Pattern.compile("(\d{1,2})");
Matcher regexMatcher = regex.matcher(text);
resultString = regexMatcher.replaceAll("$1"); // *3 ??
我想用 $1 乘以 3 替换所有出现的内容.
And I'd like to replace all occurrence with $1 multiplied by 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
It throws an 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 :(
works fine, but I can't change the $1 :(
现在,它正在工作:)
推荐答案
怎么样:
if (regexMatcher.find()) {
resultString = regexMatcher.replaceAll(
String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}
要获得第一个匹配项,请使用 #find()
.之后,您可以使用 #group(1)
来引用第一个匹配项,并将所有匹配项替换为第一个 maches 值乘以 3.
To get the first match, use #find()
. After that, you can use #group(1)
to refer to this first match, and replace all matches by the first maches value multiplied by 3.
如果你想用匹配的值乘以 3 来替换每个匹配:
And in case you want to replace each match with that match's value multiplied by 3:
Pattern p = Pattern.compile("(\d{1,2})");
Matcher m = p.matcher("12 54 1 65");
StringBuffer s = new StringBuffer();
while (m.find())
m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
System.out.println(s.toString());
您可能需要查看Matcher
的文档,其中详细介绍了这一点以及更多内容.
You may want to look through Matcher
's documentation, where this and a lot more stuff is covered in detail.
这篇关于Java 正则表达式替换为捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!