Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

Looking for quick, simple way in Java to change this string

" hello     there   " 

to something that looks like this

"hello there" 

where I replace all those multiple spaces with a single space, except I also want the one or more spaces at the beginning of string to be gone.

Something like this gets me partly there

String mytext = " hello     there   "; mytext = mytext.replaceAll("( )+", " "); 

but not quite.

like image 974
Nessa Avatar asked May 28 '10 20:05

Nessa


People also ask

How do you remove leading and trailing spaces from a string in Java?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

How do I remove extra spaces from a string?

Use JavaScript's string. replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s . Expand the whitespace selection from a single space to multiple using the \s+ RegEx.

How do I replace multiple spaces in single space?

The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.

What delete the trailing and leading spaces from a given string?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.


2 Answers

Try this:

String after = before.trim().replaceAll(" +", " "); 

See also

  • String.trim()
    • Returns a copy of the string, with leading and trailing whitespace omitted.
  • regular-expressions.info/Repetition

No trim() regex

It's also possible to do this with just one replaceAll, but this is much less readable than the trim() solution. Nonetheless, it's provided here just to show what regex can do:

    String[] tests = {         "  x  ",          // [x]         "  1   2   3  ",  // [1 2 3]         "",               // []         "   ",            // []     };     for (String test : tests) {         System.out.format("[%s]%n",             test.replaceAll("^ +| +$|( )+", "$1")         );     } 

There are 3 alternates:

  • ^_+ : any sequence of spaces at the beginning of the string
    • Match and replace with $1, which captures the empty string
  • _+$ : any sequence of spaces at the end of the string
    • Match and replace with $1, which captures the empty string
  • (_)+ : any sequence of spaces that matches none of the above, meaning it's in the middle
    • Match and replace with $1, which captures a single space

See also

  • regular-expressions.info/Anchors
like image 118
polygenelubricants Avatar answered Sep 29 '22 03:09

polygenelubricants


You just need a:

replaceAll("\\s{2,}", " ").trim(); 

where you match one or more spaces and replace them with a single space and then trim whitespaces at the beginning and end (you could actually invert by first trimming and then matching to make the regex quicker as someone pointed out).

To test this out quickly try:

System.out.println(new String(" hello     there   ").trim().replaceAll("\\s{2,}", " ")); 

and it will return:

"hello there" 
like image 42
sarah.ferguson Avatar answered Sep 29 '22 04:09

sarah.ferguson