Extracting each word from a string using Regex in Java

Java Programming Java8Object Oriented Programming

A word represents continous letters from a to z or A to Z. Using Regex that matches any letter from a-z and A-Z will suffice the need. We'll use the following regex pattern −

[a-zA-Z]+
  • [a-z] matches any character from a to z.
  • [A-Z] matches any character from A to Z.
  • + matches 1 or more characters from the group.

Example

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tester {
   public static void main(String[] args) {

      String candidate = "this is a test, A TEST.";
      String regex = "[a-zA-Z]+";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(candidate);

      System.out.println("INPUT: " + candidate);
      System.out.println("REGEX: " + regex + "\r\n");
      while (m.find()) {
         System.out.println(m.group());
      }
   }
}

This will produce the following result −

Output

this
is
a
test
A
TEST
raja
Published on 13-Aug-2018 13:45:11
Advertisements