Character class: intersection - Java regular expressions

JavaObject Oriented ProgrammingProgramming

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 intersection variant of the character class allows you to match a character which is common in the ranges that have intersection relation between them.

An intersection relation between ranges is defined using && i.e. the expression [a-z&&[r-u]] matches a single character from r to u.


 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.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[a-z&&[r-u]]";
      //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()) {
      System.out.println("Number of matched characters: "+count);


Enter input text:
how are you welcome to tutorialspoint
Number of matched characters: 9
Published on 10-Jan-2020 17:04:45