In this article, we are going to look at how to split a String using a regular expression pattern .
Contents
- Split string using split(regex) method
We can use String.split(regex) method to split a string using a pattern. This method takes a regular expression as input and divide the input array into substring based on the pattern matching.
For example, if you want to split the string "Hello World! This is my test program" using " " space separated text into words.
import java.util.Arrays;
public class SplitString {
public static void main(String[] args) {
String s1 = "Hello World! This is my test program";
String[] wordsAfterSplit = s1.split(" ");
System.out.println(Arrays.toString(wordsAfterSplit));
}
}
When you run the above program, you will get the below output. As you can see text is split into multiple words that are space separated.
[Hello, World!, This, is, my, test, program]
If you want to limit the number of tokens that the output should be split into, you can use String.split(regex, limit) method for this.
import java.util.Arrays;
public class SplitString {
public static void main(String[] args) {
String s1 = "Hello World! This is my test program";
String[] splitStringsWithLimitation = s1.split(" ", 2);
System.out.println(Arrays.toString(splitStringsWithLimitation));
}
}
When you run the above program, you will get the below output. As you can see text is split into two tokens only that are space sepaarted from the beginning.
[Hello, World! This is my test program]
Above example complete source code can be found at Github