Java中使用.*的正则表达式分组和replaceAll会重复替换 [英] Regexp grouping and replaceAll with .* in Java duplicates the replacement
问题描述
在Java中使用Rexexp时遇到问题.该示例代码写出 ABC_012_suffix_suffix
,我期望它输出 ABC_012_suffix
I got a problem using Rexexp in Java. The example code writes out ABC_012_suffix_suffix
, I was expecting it to output ABC_012_suffix
Pattern rexexp = Pattern.compile("(.*)");
Matcher matcher = rexexp.matcher("ABC_012");
String result = matcher.replaceAll("$1_suffix");
System.out.println(result);
我知道replaceAll会替换所有匹配的组,问题是为什么这个正则表达式组(.*)
在Java中我的字符串 ABC_012
上匹配两次?
I understand that replaceAll replaces all matched groups, the questions is why is this regexp group (.*)
matching twice on my string ABC_012
in Java?
推荐答案
可能是.*
给您完全匹配",然后将匹配减少为空匹配"(但仍然是匹配).尝试使用(.+)
或(^.* $)
.两者都按预期工作.
Probably .*
gives you "full match" and then reduces match to the "empty match" (but still a match). Try (.+)
or (^.*$)
instead. Both work as expected.
在regexinfo中,星形的定义如下:
At regexinfo star is defined as follows:
*(星号)-重复上一个项目零次或多次.贪婪,因此在尝试对前一项进行较少匹配的置换之前,将匹配尽可能多的项,直到前一项根本不匹配为止.
*(star) - Repeats the previous item zero or more times. Greedy, so as many items as possible will be matched before trying permutations with less matches of the preceding item, up to the point where the preceding item is not matched at all.
这篇关于Java中使用.*的正则表达式分组和replaceAll会重复替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!