English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to use Java RegEx to match a series of characters

To match a certain range of characters, that is, to match all characters between two specified characters in a sequence, the character class can be used as 

[a-z]
  • expression " [a-zA-Z] accepts any English letter.

  • expression " [0-9 &&[^ 35]] accept3and5other numbers.

Example1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Read 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]*$";
      //Compile Regular Expression
      Pattern pattern = Pattern.compile(regex);
      //Search Matcher Object
      Matcher matcher = pattern.matcher(input);
      if(matcher.matches()) {
         System.out.println("Match Occurred");
      } else {
         System.out.println("Match Not Occurred");
      }
   }
}

Output1

Enter a String
Hello
Match Occurred

Output2

Enter a String
sample#
Match Not Occurred

Example2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Read String from User
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "[0-9&&[^35]]";
      //Compile Regular Expression
      Pattern pattern = Pattern.compile(regex);
      //Search Matcher Object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("Occurrences :");+count);
   }
}

Output Result

Enter a String
111223333555689
Occurrences :8