Java group replacements regexp

Is there a way to convert a string

"m1, m2, m3" 

next

 "m1/build, m2/build, m3/build" 

only using the String.replaceAll(regex, replacement) method?

So far this is my best attempt:

 System.out.println("m1, m2, m3".replaceAll("([^,]*)", "$1/build")); >>> m1/build/build, m2/build/build, m3/build/build 

As you can see, the output is incorrect. However, using the same regexp on Linux sed gives the correct result:

 echo 'm1, m2, m3' | sed -e 's%\([^,]*\)%\1/build%g' >>> m1/build, m2/build, m3/build 
+6
source share
2 answers

([^,]*) can match an empty string, it can even match between two spaces. Try ([^,]+) or (\w+) .

Another minor note - you can use $0 to refer to the entire line with the line, avoiding the captured group:

 System.out.println("m1, m2, m3".replaceAll("\\w+", "$0/build")); 
+4
source

If you look at the problem from the other end (quite literally!), You get an expression that searches for terminators, not content. This expression works much better:

 System.out.println("m1, m2, m3".replaceAll("(\\s*(,|$))", "/build$1")); 

Here is a link to this program on ideone .

+5
source

Source: https://habr.com/ru/post/920458/


All Articles