How to match a range of characters using Java regex

JavaObject Oriented ProgrammingProgramming

To match a range of characters i.e. to match all the characters between two specified characters in a sequence you can use the character class as 

[a-z]
  • The expression “[a-zA-Z]” accepts any English alphabet.

  • The expression “[0-9&&[^35]]” accepts numbers except 3 and 5.

Example 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "^[a-zA-Z0-9]*$";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.matches()) {
         System.out.println("Match occurred");
      } else {
         System.out.println("Match not occurred");
      }
   }
}

Output 1

Enter a String
Hello
Match occurred

Output 2

Enter a String
sample#
Match not occurred

Example 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "[0-9&&[^35]]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("Occurrences :"+count);
   }
}

Output

Enter a String
111223333555689
Occurrences :8
raja
Published on 19-Nov-2019 11:52:02
Advertisements