Home > front end >  How to substitute blanks between certain patterns using regex
How to substitute blanks between certain patterns using regex

Time:01-20

I want to substitute the blanks between the $# and the ending #.

Test String:

This is my variable A $#testpattern 1# and this is variable B $#testpattern 2 with multiple blanks#

Expected result:

This is my variable A $#testpattern1# and this is variable B $#testpattern2withmultipleblanks#

I got it to work when it only has one blank but with more than one it does not work.

Current Regex:

/(?<=\$#)(\w*?)(\s*?)(\w*?)(?=#)

CodePudding user response:

Java supports a finite quantifier in a lookbehind assertion, so you can add optional word characters or spaces to it [\w\s]{0,100} and for the lookahead you can add only [\w\s]* matching 1 or more whitespace characters in between.

(?<=\$#[\w\s]{0,100})\s (?=[\w\s]*#)

For example

String string = "This is my variable A $#testpattern 1# and this is variable B $#testpattern 2 with multiple blanks#";
System.out.println(string.replaceAll("(?<=\\$#[\\w\\s]{0,100})\\s (?=[\\w\\s]*#)", ""));

Output

This is my variable A $#testpattern1# and this is variable B $#testpattern2withmultipleblanks#

See a Java demo and a Regex demo.

CodePudding user response:

Here is one way to do it.

  • \\$#(.*?)# - capture string between delimiters
  • find each capture group in the pattern.
  • remove the blanks in that group.
  • then in the original string, replace the captured string with the modified string.
String s = "This is my variable A $#testpattern 1# and this is variable B $#testpattern 2 with multiple blanks#";

Pattern p = Pattern.compile("\\$#(.*?)#");
Matcher m =p.matcher(s);
while (m.find()) {
    String str = m.group(1).replace(" ","");
    s = s.replace(m.group(1),str);
}
System.out.println(s);

prints

This is my variable A $#testpattern1# and this is variable B $#testpattern2withmultipleblanks#
  •  Tags:  
  • Related