Java 中的正则表达式,\\s 与 \\s+

2022-08-31 10:02:24

以下两个表达式之间有什么区别?

x = x.replaceAll("\\s", "");
x = x.replaceAll("\\s+", "");

答案 1

第一个匹配单个空格,而第二个匹配一个或多个空格。它们是所谓的正则表达式量词,它们执行如下匹配(取自文档):

Greedy quantifiers
X?  X, once or not at all
X*  X, zero or more times
X+  X, one or more times
X{n}    X, exactly n times
X{n,}   X, at least n times
X{n,m}  X, at least n but not more than m times

Reluctant quantifiers
X?? X, once or not at all
X*? X, zero or more times
X+? X, one or more times
X{n}?   X, exactly n times
X{n,}?  X, at least n times
X{n,m}? X, at least n but not more than m times

Possessive quantifiers
X?+ X, once or not at all
X*+ X, zero or more times
X++ X, one or more times
X{n}+   X, exactly n times
X{n,}+  X, at least n times
X{n,m}+ X, at least n but not more than m times

答案 2

这两个调用将始终产生相同的结果,无论是什么。但是,请务必注意,这两个正则表达式并不相同:replaceAllx

  • \\s- 匹配单个空格字符
  • \\s+- 匹配一个或多个空格字符的序列。

在这种情况下,它没有区别,因为您将所有内容替换为空字符串(尽管从效率的角度来看使用会更好)。如果用非空字符串替换,则两者的行为会有所不同。\\s+