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 range variant of the character class allows you to use a range of characters i.e the expression [a-z] matches a single character from the alphabets a to z and the expression [^A-Z] matches a character which is not a capital letter.
Example 1
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]"; //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 range (a-z): "+count); } }
Output
Enter input text: sample data 5423 #@ %*& Number characters from the range (a-z): 10
Example 2
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample3 { 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]"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(input); int count =0; if (matcher.find()) { System.out.println("match occurred"); } else { System.out.println("match not occurred"); } } }
Output 1
Enter input text: sample data match occurred
Output 2
Enter input text: SAMPLEDATA match not occurred