为什么'replaceAll'方法不在String的开头加一个空的space?

Why does the 'replaceAll' method not add an empty space at the beginning of the String?

我有一个在开头、中间和结尾有多个白色 space 的字符串: " Humpty Dumpty sat ".

我使用正则表达式 () 删除多余的白色 space 并将其替换为第 1 组(这是一个空的 space)。

String str = "        Humpty   Dumpty   sat  ";
str = str.replaceAll("^ +| +$|( )+", "");
System.out.println("[" + str + "]");

预期输出:

[ Humpty Dumpty sat ]

实际输出:

[Humpty Dumpty sat]

替换字符串是在搜索和替换过程中每个正则表达式匹配被替换的文本。 String 开头的大白space 应该被替换为空的space。 这里为什么不在String的开头加一个空的space?

一个简单的解决方案是用一个空白字符替换一系列 multiple 空白字符。

演示:

public class Main {
    public static void main(String args[]) {
        String str = "     Humpty   Dumpty   sat ";
        System.out.println("->" + str + "<-");

        str = str.replaceAll("\s+", " ");
        System.out.println("->" + str + "<-");
    }
}

输出:

->     Humpty   Dumpty   sat <-
-> Humpty Dumpty sat <-

我不知道你的目标是什么,但如果你只想删除单词之间的额外空格,那么我建议使用环视:

String str = "        Humpty   Dumpty   sat  ";
String output = str.replaceAll("\b(\w+)[ ]{2,}(?=\w)", " ");
System.out.println("|" + input + "|");
System.out.println("|" + output + "|");

这会打印:

|        Humpty   Dumpty   sat  |
|        Humpty Dumpty sat  |

Why did it not add an empty space, here, at the beginning of the String?

因为您使用的正则表达式专门设计为不在字符串的开头或结尾添加 spaces:

str.replaceAll("^ +| +$|( )+", "");

这里我们有三个选择:^ + +$( )+。所有三个备选方案都匹配一个或多个 space。区别在于前两个只分别匹配字符串的开头和结尾,只有第三个包含捕获组。因此,如果第三个匹配,即如果 spaces 的序列不在字符串的开头或结尾,则 的值将是 space。否则为空。

这样做的重点是不要在开头或结尾添加 spaces。如果您不想要这种行为,则不需要任何这种复杂性。只需将一个或多个 space 替换为单个 space 即可。

replaceAll执行多次替换时,任何捕获只有在当前替换期间匹配时才可用。无法使用从较早或较晚的比赛中捕获的内容。

这意味着当替换字符串开头和结尾的空格时,</code> 不可用,因为 <code>( )+ 交替不匹配。 </code> 仅在非锚定交替匹配时在字符串中间可用。</p> <p>我们可以在一个更简单的例子中看到这一点:</p> <pre><code>String str = "foobar"; System.out.println(str.replaceAll("(foo)|bar", "<>"));

如果 </code> 被记住,那么我们希望看到这个输出:</p> <pre><code><foo><foo>

但事实并非如此。实际输出有一个空白,其中 bar 曾经是:

<foo><>

这说明</code>在匹配到<code>foo后清空,替换bar时为空