Issue
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*?)(?=#)
Solution
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.
Answered By - The fourth bird
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.