Home > Mobile >  Java Regex : Replace characters between two specific characters with equal number of another charact
Java Regex : Replace characters between two specific characters with equal number of another charact

Time:09-25

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.

CodePudding user response:

You can use this replacement using look around assertions:

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

enter image description here

  • Related