Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing whitespace from strings in Groovy

Tags:

string

groovy

I have a string like

String  str = "My name is Monda" 

How can I achieve a string like

str  = "MynameisMonda" 
like image 705
monda Avatar asked Sep 21 '13 19:09

monda


People also ask

How do you remove white spaces from a string?

The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".

How do I cut a string in Groovy?

The Groovy community has added a take() method which can be used for easy and safe string truncation. Both take() and drop() are relative to the start of the string, as in "take from the front" and "drop from the front". Show activity on this post. In Groovy, strings can be considered as ranges of characters.

How do I remove a character from a string in Groovy?

Groovy has added the minus() method to the String class. And because the minus() method is used by the - operator we can remove parts of a String with this operator. The argument can be a String or a regular expression Pattern. The first occurrence of the String or Pattern is then removed from the original String.

How do I remove the first character from a string in Groovy?

replaceAll() Method. Just like replaceFirst(), the replaceAll() also accepts a regular expression and given replacement. It replaces each substring that matches the given criteria. To remove a prefix, we can use this method too.


2 Answers

You can use the replaceAll() function.

For your case:

replaceAll("\\s","") 

where \s means any whitespace (such as a space character).

like image 79
user711189 Avatar answered Oct 13 '22 16:10

user711189


You just need this function. replaceAll()

str.replaceAll("\\s","") 

\s = Anything that is a space character (including space, tab characters etc)

You need to escape the backslash if you want \s to reach the regex engine, resulting in \s. Like wise we use :-

\S = Anything that isn't a space character (including both letters and numbers, as well as punctuation etc)

\w = Anything that is a word character

\W = Anything that isn't a word character (including punctuation etc)

like image 31
Dhanendra Pratap Singh Avatar answered Oct 13 '22 17:10

Dhanendra Pratap Singh