Java Regex - reduce spaces in a string

前端 未结 4 1306
刺人心
刺人心 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.

提交回复
热议问题