In this example, let’s see how to split a string using regular expression.
Source Code
package com.beginner.examples;
import java.util.regex.Pattern;
public class SplitString {
public static void main(String[] args) {
String str = "Hello World";
/*
* Use regular expression pattern to split a string.
*/
Pattern pattern = Pattern.compile("(World)");
String[] parts = pattern.split(str);
for(String p:parts){
System.out.println(p);
}
}
}
Output:
Hello
References
Imported packages in Java documentation: