Reputation: 31
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
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
Reputation: 786359
You can use this replacement using look around assertions:
String repl = s.replaceAll("(?<=-)\\+(?=-)", "-");
//=> +-----+
(?<=-)\\+(?=-)
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