Whitespace Matching Regex - Java
In Java, you can use the following regular expression to match any amount of whitespace:
This regular expression uses the
\s character class, which matches any whitespace character (such as a space, tab, or newline). The
+ quantifier indicates that one or more whitespace characters should be matched.
Here is an example of how to use this regular expression to split a string on whitespace:
String input = "Hello World"; String words = input.split("\\s+");
This will split the string on any amount of consecutive whitespace, resulting in the following array:
You can also use this regular expression to search for whitespace in a string or to replace whitespace with another string.
For example, to replace all whitespace in a string with a single space, you can use the following code:
String input = "Hello World"; String output = input.replaceAll("\\s+", " ");
This will replace all consecutive whitespace with a single space, resulting in the following string: