Use a character class in Java Regular Expressions

Java 8Object Oriented ProgrammingProgramming

A character class is set of characters that are enclosed inside square brackets. The characters in a character class specify the characters that can match with a character in an input string for success. An example of a character class is [a-z] which denotes the alphabets a to z.

A program that demonstrates a character class in Java Regular Expressions is given as follows:

Example

 Live Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("[a-z]+");
      Matcher m = p.matcher("the sky is blue");
      System.out.println("The input string is: the sky is blue");
      System.out.println("The Regex is: [a-z]+");
      System.out.println();
      while (m.find()) {
         System.out.println("Match: " + m.group());
      }
   }
}

Output

The input string is: the sky is blue
The Regex is: [a-z]+
Match: the
Match: sky
Match: is
Match: blue

Now let us understand the above program.

The subsequence “[a-z]+” is searched in the string sequence "the sky is blue". Here a character class is used i.e. [a-z] which denotes the alphabets a to z. The find() method is used to find if the subsequence is in the input sequence and the required result is printed. A code snippet which demonstrates this is as follows:

Pattern p = Pattern.compile("[a-z]+");
Matcher m = p.matcher("the sky is blue");
System.out.println("The input string is: the sky is blue");
System.out.println("The Regex is: [a-z]+");
System.out.println();
while (m.find()) {
   System.out.println("Match: " + m.group());
}
raja
Published on 19-Feb-2019 11:34:31
Advertisements