2

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
  • You should include how it's not working. What you get instead. Commented Sep 25, 2021 at 9:09
  • If my answer did not solve your issue please consider updating the question. Commented Nov 28, 2021 at 19:47

2 Answers 2

1

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.

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

Comments

0

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.

2 Comments

FYI: Here is a link to the regex debugger. If anyone wants to see how matches are now found in the current string, please click ▶️ button.
I tried to put it into a snippet, which works. But it requires the user to both expand and run it.

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.