Java regex program to split a string at every space and punctuation.


The regular expression "[!._,'@?//s]" matches all the punctuation marks and spaces.

Example

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main( String args[] ) {
      String input = "This is!a.sample"text,with punctuation!marks";
      Pattern p = Pattern.compile("[!._,'@?//s]");
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
      }
      System.out.println("Number of matches: "+count);
   }
}

Output

Number of matches: 8

The split() method of the String class accepts a value representing a regular expression and splits the current string into array of tokens (words), treating the string between the occurrence of two matches as one token.

For example, if you pass single space " " as a delimiter to this method and try to split a String. This method considers the word between two spaces as one token and returns an array of words (between spaces) in the current String.

Therefore, to split a string at every space and punctuation, invoke the split() method on it by passing the above specified regular expression as a parameter.

Example

 Live Demo

import java.util.Scanner;
import java.util.StringTokenizer;
public class RegExample {
   public static void main( String args[] ) {
      String regex = "[!._,'@? ]";
      System.out.println("Enter a string: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      StringTokenizer str = new StringTokenizer(input,regex);
      while(str.hasMoreTokens()) {
         System.out.println(str.nextToken());
      }
   }
}

Output

Enter a string:
This is!a.sample text,with punctuation!marks@and_spaces
This
is
a
sample
text
with
punctuation
marks
and
spaces

Updated on: 10-Jan-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements