Regexp grouping and replaceAll c. * In Java duplicate replacement

I am having a problem using Rexexp in Java. The sample code writes out ABC_012_suffix_suffix, I expected it to outputABC_012_suffix

    Pattern rexexp  = Pattern.compile("(.*)");
    Matcher matcher = rexexp.matcher("ABC_012");
    String  result  = matcher.replaceAll("$1_suffix");

    System.out.println(result);

I understand that replaceAll replaces all mapped groups, so why does this regexp group (.*)match on my line ABC_012in Java?

+5
source share
3 answers

Probably .*gives you a “perfect match” and then reduces the match to an “empty match” (but still matches). Try (.+)or instead (^.*$). Both work as expected.

In the star, regexinfo is defined as follows:

* () - . , , , , .

+5
Pattern regexp  = Pattern.compile(".*");
Matcher matcher = regexp.matcher("ABC_012");
matcher.matches();
System.out.println(matcher.group(0));
System.out.println(matcher.replaceAll("$0_suffix"));

:

ABC_012
ABC_012_suffix_suffix

replaceAll: find , :

while (matcher.find()) {
  System.out.printf("Start: %s, End: %s%n", matcher.start(), matcher.end());
}

:

Start: 0, End: 7
Start: 7, End: 7

, , "ABC_012" "". "_suffix" :

"ABC_012" + "_suffix" + "" + "_suffix"
+6

"_suffix" , :

String result = "ABC_012" + "_suffix";

?

+3

All Articles