简体   繁体   中英

Regex to remove spaces

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.

The following will do it:

str = str.replaceAll(" ", "");

Alternatively:

str = str.replaceAll(" +", "");

In my benchmarks, the latter was ~40% faster than the former.

String str = "     ";
str = str.replaceAll("\\s+","");

you can do -

str = str.replace(" ", "");
str = str.replaceAll(" +", "");

If you check definition of replace and replaceAll 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

Why not try a simple /[ ]+/ ? This should be what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM