How to Split String Using Regex in Java: Simple Guide
In Java, you can split a string using regex by calling
split() method on a string object with a regex pattern as the argument. For example, str.split("\\s+") splits the string at one or more whitespace characters.Syntax
The basic syntax to split a string using regex in Java is:
String[] parts = inputString.split("regexPattern");Here:
- inputString is the string you want to split.
- regexPattern is the regular expression defining where to split.
- The method returns an array of strings split at matches of the regex.
java
String[] parts = inputString.split("regexPattern");
Example
This example shows how to split a sentence into words using whitespace as the separator with regex "\\s+" which means one or more spaces.
java
public class SplitExample { public static void main(String[] args) { String sentence = "Java is fun to learn"; String[] words = sentence.split("\\s+"); for (String word : words) { System.out.println(word); } } }
Output
Java
is
fun
to
learn
Common Pitfalls
Common mistakes include:
- Not escaping special regex characters properly (like dot
.or backslash\\). - Using
split(".")which splits at every character because dot means any character in regex. - Expecting
split()to remove empty strings when delimiters are adjacent (it keeps empty strings unless you limit the result).
Correct usage requires escaping special characters with double backslashes.
java
public class SplitPitfall { public static void main(String[] args) { String data = "one.two.three"; // Wrong: splits at every character because '.' means any char String[] wrong = data.split("."); System.out.println("Wrong split length: " + wrong.length); // Right: escape dot to split at literal '.' String[] right = data.split("\\."); System.out.println("Right split length: " + right.length); } }
Output
Wrong split length: 0
Right split length: 3
Quick Reference
- split(regex): splits string by regex, returns array.
- Escape special chars: use double backslash
\\for regex metacharacters. - Limit parameter:
split(regex, limit)controls max splits and trailing empty strings.
Key Takeaways
Use
split() method with a regex string to split Java strings by patterns.Always escape regex special characters with double backslashes in Java strings.
Regex like
"\\s+" splits on one or more whitespace characters.Beware that
split(".") splits at every character because dot means any character.Use the optional limit parameter to control the number of splits and handle empty strings.