Java Regular Expression character classes

Introduction

To match any sequence that contains one or more characters in any order, use character class.

A character class defines a set of characters.

A character class is created by putting the characters to match between brackets.

For example, to match whole words, match any sequence of the letters of the alphabet. To match the lowercase characters a through z, use [a-z].

// Use a character class. 
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String args[]) {
    // Match lower case words.
    Pattern pat = Pattern.compile("[a-z]+");
    Matcher mat = pat.matcher("this is a test.");

    while (mat.find())
      System.out.println("Match: " + mat.group());
  }//from  ww w . j ava 2  s. c o m
}



PreviousNext

Related