How to write a regex to remove spaces in Java?
For example
Input : " "
Output : ""
---------------------
Input : " "
Output : ""
Note that tabs and new lines should not be removed. Only spaces should be removed.
Edit :
How do we make a check ?
For example how to check in an if statement that a String contains only spaces (any number of them)
if(<statement>)
{
//inside statement
}
For
input = " " or input = " "
The control should should go inside if statement.
String str = " ";
str = str.replaceAll("\\s+","");
The following will do it:
str = str.replaceAll(" ", "");
Alternatively:
str = str.replaceAll(" +", "");
In my benchmarks, the latter was ~40% faster than the former.
you can do -
str = str.replace(" ", "");
str = str.replaceAll(" +", "");
If you check definition of replace
andreplaceAll
method -
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
Unless you really need to replace a regular expression, replaceAll
is definitely not our choice. Even if the performance is acceptable, the amount of objects created will impact the performance.
Not that much different from the replaceAll()
, except that the compilation time of the regular expression (and most likely the execution time of the matcher) will be a bit shorter when in the case of replaceAll()
.
Its better to use replace
method rather replaceAll
.
Real-time comparison
File size -> 6458400
replaceAll -> 94 millisecond
replace -> 78 millisecond
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