Home > Java > javaTutorial > How to Split Strings on Any Whitespace in Java Using Regex?

How to Split Strings on Any Whitespace in Java Using Regex?

Mary-Kate Olsen
Release: 2024-12-24 03:00:13
Original
329 people have browsed it

How to Split Strings on Any Whitespace in Java Using Regex?

Splitting Strings on Any Whitespace Using Regex Patterns

To split a string using any whitespace character as a delimiter in Java, utilize the java.lang.String.split() method with an appropriate regex pattern.

The regex pattern to achieve this is \s . This pattern matches one or more occurrences of any whitespace character, such as spaces, tabs, newlines, etc.

Example:

Consider the following string:

myString = "Hello[space character][tab character]World"
Copy after login

Using the split() method with the pattern \s , we can split the string as follows:

String[] splitString = myString.split("\s+");
Copy after login

This will result in an array with two elements:

  • "Hello"
  • "World"

The split operation will ignore the whitespace characters between "Hello" and "World".

Escaping Backslashes:

Note that the backslash character in the regex pattern must be escaped in Java. This is because Java first tries to interpret escaped sequences, such as n for a newline. To escape the backslash, use \. Therefore, the final pattern becomes "\s ".

The above is the detailed content of How to Split Strings on Any Whitespace in Java Using Regex?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template