Character class: union - Java regular expressions


The character classes in Java regular expression is defined using the square brackets "[ ]", this subexpression matches a single character from the specified or, set of possible characters. For example the regular expression [abc] matches a single character a or, b or, c.

The union variant of the character class allows you to match a character from one of the specified ranges i.e. the expression [a-z[0-9]] matches a single character which is either a small alphabet (a-z) or a digit (0-9).

Example

 Live Demo

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample1 {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[a-z[0-9]]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("Number characters from the ranges (a-z or 0-9): "+count);
   }
}

Output

Enter input text:
sample DATA 12345
Number characters from the ranges (a-z or 0-9): 11

Updated on: 13-Jan-2020

433 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements