How to Split a String Using Regular Expression in Java


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:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments