Java Regex - reduce spaces in a string

前端 未结 4 1293
刺人心
刺人心 2020-12-16 00:42

I don\'t have time to get my head around regex and I need a quick answer. Platform is Java.

I need the string

\"Some text   with  spaces\"
<         


        
相关标签:
4条回答
  • 2020-12-16 01:17

    You need to use a constant of java.util.regex.Pattern for avoid recompiled the expression every time:

    private static final Pattern REGEX_PATTERN = 
            Pattern.compile(" {2,}");
    
    public static void main(String[] args) {
        String input = "Some text   with spaces";
        System.out.println(
            REGEX_PATTERN.matcher(input).replaceFirst(" ")
        );  // prints "Some text with spaces"
    }
    

    In another way, the Apache Commons Lang include in the class StringUtils the method normalizeSpace.

    0 讨论(0)
  • 2020-12-16 01:20

    If we're talking specifically about spaces, you want to be testing specifically for spaces:

    MyString = MyString.replaceAll(" +", " ");
    

    Using \s will result in all whitespace being replaced - sometimes desired, othertimes not.

    Also, a simpler way to only match 2 or more is:

    MyString = MyString.replaceAll(" {2,}", " ");
    

    (Of course, both of these examples can use \s if any whitespace is desired to be replaced with a single space.)

    0 讨论(0)
  • 2020-12-16 01:28
    String a = "Some    text  with   spaces";
    String b = a.replaceAll("\\s+", " ");
    assert b.equals("Some text with spaces");
    
    0 讨论(0)
  • 2020-12-16 01:44

    For Java (not javascript, not php, not anyother):

    txt.replaceAll("\\p{javaSpaceChar}{2,}"," ")
    
    0 讨论(0)
提交回复
热议问题