且构网

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

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

更新时间:2022-12-28 15:37:59

试试这个:

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
        • regular-expressions.info/Anchors