目标是用括号标记字符串中的每个匹配项,并为每个匹配项标记返回相同的字符串
即:
Pattern = "\\d+"
Text = "e3e3e"
wanted result = "e(3)e(3)e"
我尝试过:
while (matcher.find())
text = text.replace(match.group(), "(" + match.group() + ")");
但每次找到匹配项时它都会一遍又一遍地替换所有匹配项
e3e3e => e((3))e((3))e instead of e(3)e(3)e
h4h444h = > h(4)h(4)(4)(4)h instead of h(4)h(444)h
最佳答案
您可以将匹配项替换为 ($0)
,其中 $0
代表整个匹配项:
String Pattern = "\\d+";
String Text = "e3e3e";
System.out.println(Text.replaceAll(Pattern, "($0)"));
请参阅Java demo和 regex demo .
Group zero always stands for the entire expression.
关于java - 正则表达式 : mark every match in the string and return the string edited with marks, Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47840310/