Pattern Matching Using Character Classes
Learn how to create pattern objects using character classes and search for the given pattern within any text.
Character classes
A character class is a group of characters that represent patterns. It is made up of brackets followed by a series of characters, e.g. [aeiou]
, This would match any vowel within your string.
You can specify multiple options in one character class, e.g. [a-zA-Z0-9]
will match upper and lower case letters and numbers within your string.
Below are few examples of simple character classes:
The character class [abc]
The character class [abc]
will match any one character from the set {a
, b
, c
}.
Execute the code below to see this in action.
Press + to interact
import java.util.regex.*;class Main {public static void main( String args[] ) {System.out.println(Pattern.matches("[abc]", "xyz")); // falseSystem.out.println(Pattern.matches("[abc]", "a")); // trueSystem.out.println(Pattern.matches("[abc]", "aabbcc")); //false}}
Explanation:
- false