Java – replaceall boundaries and exceptions

I'm trying to use replaceall to eliminate all spaces in the string, except 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

At present, it outputs ABCD #ef ## GH #ijklm without distinguishing # characters Is there any way to use regular expressions on replaceall?

String s1 = "AB CD #E     F# #GH   I# JK L   M";
s1 = s1.replaceAll("\\s+","");
System.out.println(s1);

Solution

I'm not good at regular expressions I'll use a loop

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);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>