regex
Strip extra spaces in a string
With this example we are going to demonstrate how to strip extra spaces in a String. In short, to strip extra spaces in a String you should:
- Use a given String with spaces between words.
- Use
replaceAll(String regex, String replacement)
API method of String, with a given regular expression. The regular expression is constructed by the white character between the “>” “<” characters. This method replaces each substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expressionjava.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)
. - Print the given String and the result String to check the change between the two Strings.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; public class StripSpaces { public static void main(String[] args) { String str = "<a>test 1</a> <b>test 2</b> "; String output = str.replaceAll(">\s+<", "><"); System.out.println(str); System.out.println(output); } }
Output:
<a>test 1</a> <b>test 2</b>
<a>test 1</a><b>test 2</b>
This was an example of how to strip extra spaces in a String in Java.