Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to remove spaces

Tags:

java

regex

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.

like image 465
user2434 Avatar asked May 15 '12 07:05

user2434


3 Answers

String str = "     ";
str = str.replaceAll("\\s+","");
like image 169
Ertuğrul Çetin Avatar answered Nov 18 '22 07:11

Ertuğrul Çetin


The following will do it:

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

Alternatively:

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

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

like image 38
NPE Avatar answered Nov 18 '22 06:11

NPE


you can do -

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

If you check definition of replaceandreplaceAll 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
like image 1
Subhrajyoti Majumder Avatar answered Nov 18 '22 07:11

Subhrajyoti Majumder