Matching from a set of characters Java regualr expression



The character classes in Java regular expression is defined using the square brackets "[ ]", the character class 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. Similarly, "[a-z]" matches a character from a to z.

Example 1

 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.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 of characters from a to z: "+count);    } }

Output

Enter input text: sample data 1234$ Number of characters from a to z: 10

Example 2

 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.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 of non-alphabetic characters : "+count);    } }

Output

Enter input text: sample data 1234$ Number of non-alphabetic characters : 7
Updated on: 2020-01-13T06:09:00+05:30

137 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements