Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replaceAll boundaries and exceptions

Tags:

java

regex

I'm trying to use replaceAll to eliminate all of the whitespace in a string with the exception of two areas.

If my string is

AB CD #E     F# #GH   I# JK L   M

then I want it to output as

ABCD#E     F##GH   I#IJKLM

Currently, it is outputting ABCD#EF##GH#IJKLM without discriminating the # characters. Is there a way to do that with regular expressions on replaceAll?

String s1 = "AB CD #E     F# #GH   I# JK L   M";
s1 = s1.replaceAll("\\s+", "");
System.out.println(s1);
like image 319
rusty Avatar asked Aug 30 '26 09:08

rusty


1 Answers

I'm not good at regular expressions. I will use a loop for this.

String s1 = "AB CD #E     F# #GH   I# JK L   M";
StringBuilder sb = new StringBuilder();
boolean keepSpace = false;
for(int i = 0; i < s1.length; i++){
    char c = s1.charAt(i);
    if(keepSpace || c != ' ')
        sb.append(c);
    if(c == '#')
        keepSpace = !keepSpace;
}
s1 = sb.toString();
System.out.println(s1);
like image 66
johnchen902 Avatar answered Aug 31 '26 23:08

johnchen902



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!