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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With