Character class: subtraction - Java regular expressions

JavaObject Oriented ProgrammingProgramming

You can subtract one range from other and use it as new range. You can achieve this by using two variants of character classes i.e. negation and intersection.

For example the intersection of ranges [a-l] and [^e-h] gives you the characters a to l as rage subtracting the characters [e-h]


 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-l&&[^e-h]]";
      //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.print(" ");
      System.out.println("Number of matched characters: "+count);


Enter input text:
a b c d i j k l Number of matched characters: 8
Updated on 10-Jan-2020 12:38:17