6

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

That's the way I was thinking of doing it. But don't you have /build and $1 swapped?
@BlackVegetable Since I'm matching the terminator, not the content, the $1 belongs at the end.
Nice. However this solution will not work if there are spaces between commas. E.g. for input 'm1 , m2, m3 ' the output would be incorrect: 'm1 /build, m2 /build,m3 /build'. The second answer which uses (\w+) as a regexp can cope with this situation.
@miso Not that it mattered much, but the "space before comma" was easy to address (please see the edit). I liked the \\w+ solution better, though :)
4

([^,]*) 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"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.