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
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.
([^,]*)
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With