Removing whitespaces using Regex in Java
Given a string, your task is to remove the whitespaces in the string using Java Regex (Regular Expressions).
Input : Hello Everyone . Output : HelloEveryone. Input : Geeks for Geeks . Output : GeeksforGeeks.
Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package.
There are numerous approaches to remove the whitespaces in the string using Regex in Java. A few of them are listed below.
- Using Regex.Matcher.replaceAll() method
- Using appendReplacement() method
1. Using Matcher.replaceAll() method
The java.util.regex.Matcher.replaceAll(String replacement) method replaces every subsequence of the input sequence that matches the pattern with the given replacement string.
public String replaceAll(String replacement)
Parameters: replacement – The replacement string.
Return Value: The string is constructed by replacing each matching subsequence with the replacement string, substituting captured subsequences as needed.
The following program demonstrates how to remove the white spaces using a matcher.replaceAll(String replacement) method of util.regex.Pattern class.
2. Using appendReplacement() method
The appendReplacement(StringBuilder, String) method of Matcher Class behaves as an append-and-replace method. This method reads the input string and replaces it with the matched pattern in the matcher string.
public Matcher appendReplacement(StringBuilder builder, String stringToBeReplaced)
Parameters: This method takes two parameters:
- builder: which is the StringBuilder that stores the target string.
- stringToBeReplaced: which is the String to be replaced in the matcher.
Return Value: This method returns a Matcher with the target String replaced.
Exception: This method throws the following exceptions:
- IllegalStateException: If no match has yet been attempted, or if the previous match operation failed.
- IllegalArgumentException: If the replacement string refers to a named-capturing group that does not exist in the pattern.
- IndexOutOfBoundsException: If the replacement string refers to a capturing group that does not exist in the pattern.
The following program demonstrates how to remove the white spaces using a matcher.appendReplacement(StringBuilder builder, String stringToBeReplaced) method of util.regex.Pattern class.