Anil Lama
Anil Lama

Reputation: 31

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

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.

Upvotes: 2

Views: 90

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

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.

Upvotes: 0

anubhava
anubhava

Reputation: 786359

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.

Upvotes: 1

Related Questions