JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Program: How to split a string using regular expression?


Description:

We can split a string using regular expression pattern. Example shows how to split the string.


Code:
package com.java2novice.regex;

import java.util.regex.Pattern;

public class MyTokens {

	public static void main(String a[]){
		
		String str = "I have a cat. I play cricket with bat. I dont like rat,"+
			"i hate mats, now break it";
		Pattern ptn = Pattern.compile("(cat|rat|mat|bat)");
		String[] parts = ptn.split(str);
		for(String p:parts){
			System.out.println(p);
		}
	}
}

Output:
I have a 
. I play cricket with 
. I dont like 
,i hate 
s, now break it
<< Previous Program 

List Of Regular Expression Sample Programs:

  1. Simple regex pattern matching using string matches().
  2. Simple java regex using Pattern and Matcher classes.
  3. Java regex with case insensitive.
  4. How to validate IP address using regular expression?
  5. How to replace a pattern using regular expression in java?
  6. How to remove multiple spaces with a single space with in a string?
  7. How to validate user name using regular expression?
  8. How to validate email address using regular expression?
  9. How to validate password using regular expression?
  10. How to validate file extensions using regular expression in java?
  11. How to validate date format using regular expression in java?
  12. How to capture or extract a value(s) from text using regular expression in java?
  13. How to split a string using regular expression?
Java2Novice - YouTube Channel
  1. Python Tutorial for Beginners
Knowledge Centre
What is adapter class?
An adapter class provides the default implementation of all methods in an event listener interface. Adapter classes are very useful when you want to process only few of the events that are handled by a particular event listener interface. You can define a new class by extending one of the adapter classes and implement only those events relevant to you.
Famous Quotations
It is easier to fight for one’s principles than to live up to them.
-- Alfred Adler

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2019 by Nataraja Gootooru. All Rights Reserved.