Java-Match Any Sequence

Match Any Sequence

Sometimes you will want to match any sequence that contains one or more characters, in any order, that are part of a set of characters. For example, to match whole words, you want to match any sequence of the letters of the alphabet. One of the easiest ways to do this is to use a character class, which defines a set of characters. For example, to match the any sequence characters, use [A-Z]+.

Program



Program Source

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

public class Javaapp {
  
    public static void main(String[] args) {
        
        Pattern pat = Pattern.compile("[A-Z]+");
        Matcher mat = pat.matcher("CAR BOX BALL cat");
        
        int i = 0;
        while(mat.find())
        {
            i++;
            System.out.println(i+"th subsequence  : "+mat.group());
        }
    }
}

Leave a Comment