且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java如何用字符串中的单个空格替换2个或多个空格并删除前导和尾随空格

更新时间:2022-12-28 16:00:26

试试这个:

String after = before.trim().replaceAll(" +", " ");

另见

  • String.trim()
    • 返回字符串的副本,省略前导和尾随空格.
    • 也可以只用一个 replaceAll 来做到这一点,但这比 trim() 解决方案可读性要差得多.尽管如此,这里提供它只是为了展示正则表达式可以做什么:

      It's also possible to do this with just one replaceAll, but this is much less readable than the trim() solution. Nonetheless, it's provided here just to show what regex can do:

        String[] tests = {
            "  x  ",          // [x]
            "  1   2   3  ",  // [1 2 3]
            "",               // []
            "   ",            // []
        };
        for (String test : tests) {
            System.out.format("[%s]%n",
                test.replaceAll("^ +| +$|( )+", "$1")
            );
        }
    

    有 3 个备选:

    • ^_+ : 字符串开头的任意空格序列
      • 匹配并替换为$1,捕获空字符串
      • ^_+ : any sequence of spaces at the beginning of the string
        • Match and replace with $1, which captures the empty string
        • 匹配并替换为$1,捕获空字符串
        • Match and replace with $1, which captures the empty string
        • 匹配并替换为 $1,捕获一个空格
        • Match and replace with $1, which captures a single space