What's the difference between the following two expressions?
x = x.replaceAll("\\s", ""); x = x.replaceAll("\\s+", "");
The Java regex pattern \\s+ is used to match multiple whitespace characters when applying a regex search to your specified value. The pattern is a modified version of \\s which is used to match a single whitespace character. The difference is easy to see with an example.
\\s - matches single whitespace character. \\s+ - matches sequence of one or more whitespace characters.
Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.
The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.
The first one matches a single whitespace, whereas the second one matches one or many whitespaces. They're the so-called regular expression quantifiers, and they perform matches like this (taken from the documentation):
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
Those two replaceAll
calls will always produce the same result, regardless of what x
is. However, it is important to note that the two regular expressions are not the same:
\\s
- matches single whitespace character \\s+
- matches sequence of one or more whitespace characters.In this case, it makes no difference, since you are replacing everything with an empty string (although it would be better to use \\s+
from an efficiency point of view). If you were replacing with a non-empty string, the two would behave differently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With