Today i play around with some funny and simple thing in Java, frankly i really do not know about it. For example, see code snippets :

if(StringUtils.hasLength(sText)
 {
     sText= sText.replaceAll(" ", " AND ");			   
}

What i trying to do is remove all whitespace between a string. for example, user key in “Hello Google”, it will replace as “Hello AND Google”, ya this is correct if user only enter one space between words.

"Hello Google"  ---> "Hello AND Google"

But how about user key in many spaces in between? For example

"Hello           Google"  ---> "Hello AND AND AND AND AND Google"

Above is not what i want, should i replace it as below?

if(StringUtils.hasLength(sText)
 {
     sText= sText.replaceAll(" ", " AND ");
     sText= sText.replaceAll("  ", " AND ");	
     sText= sText.replaceAll("   ", " AND ");	
     sText= sText.replaceAll("    ", " AND ");	
     sText= sText.replaceAll("     ", " AND ");				   
}

ya we can replace as many as we like, but this is not so effective and dynamic enough.

Solution

In this case, you should use regular expression to solve it.

if(StringUtils.hasLength(sText)
 {
     sText= sText.replaceAll("\\s+", " AND ");		   
}

Great , exactly what i want, Regular Expression ROCK!!!

Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Related Posts

Popular Posts