Java Regex : Replace characters between two specific characters with equal number of another character

Viewed 83

Replacing all characters between starting character "+" and end character "+" with the equal number of "-" characters.
My specific situation is as follows:

Input: +-+-+-+
Output: +-----+

String s = = "+-+-+-+";
s = s.replaceAll("-\\+-","---")

This is not working. How can I achieve the output in Java? Thanks in advance.

2 Answers

You can use this replacement using look around assertions:

String repl = s.replaceAll("(?<=-)\\+(?=-)", "-");
//=> +-----+

RegEx Demo

(?<=-)\\+(?=-) will match a + if it is surrounded by - on both sides. Since we are using lookbehind and lookahead therefore we are not consuming characters, these are only assertions.

The matches you have are overlapping, look:

+-+-+-+
 ^^^
    Match found and replaced by "---"

+---+-+
    ^
    +-- Next match search continues from here

WARNING: No more matches found!

To make sure there is a hyphen free for the next match, you need to wrap the trailing - with a positive lookahead and use -- as replacement pattern:

String s = = "+-+-+-+";
s = s.replaceAll("-\\+(?=-)","--")

See the regex demo.

Related