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.
trim()
Removes only the leading & trailing spaces.
From Java Doc, "Returns a string whose value is this string, with any leading and trailing whitespace removed."
"D ev Dum my"
replace(), replaceAll()
Replaces all the empty strings in the word,
Output:
Note: "\s+" is the regular expression similar to the empty space character.
Reference : https://www.codedjava.com/2018/06/replace-all-spaces-in-string-trim.html
This will match more than one space.
OUTPUT:
You just need a:
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:
and it will return:
To eliminate spaces at the beginning and at the end of the String, use
String#trim()
method. And then use yourmytext.replaceAll("( )+", " ")
.You could use lookarounds also.
OR
<space>(?= )
matches a space character which is followed by another space character. So in consecutive spaces, it would match all the spaces except the last because it isn't followed by a space character. This leaving you a single space for consecutive spaces after the removal operation.Example:
Stream version, filters spaces and tabs.