Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regexp groups replacements

Tags:

java

regex

Is there a way to transform the String

"m1, m2, m3"

to the following

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

only by using 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 in Linux's sed command gives correct output:

echo 'm1, m2, m3' | sed -e 's%\([^,]*\)%\1/build%g'
>>> m1/build, m2/build, m3/build
like image 686
Michal Vician Avatar asked Jul 13 '12 20:07

Michal Vician


2 Answers

If you look at the problem from the other end (quite literally!) you get an expression that looks for terminators, rather than for the content. This expression worked a lot better:

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

Here is a link to this program on ideone.

like image 63
Sergey Kalinichenko Avatar answered Oct 05 '22 19:10

Sergey Kalinichenko


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

Another minor note - you can use $0 to refer to the whole matched string, avoiding the captured group:

System.out.println("m1, m2, m3".replaceAll("\\w+", "$0/build"));
like image 23
Kobi Avatar answered Oct 05 '22 20:10

Kobi