Practice Programs on Character Classes and Quantifiers

1. Match Digits Using Character Class and Quantifier

This program uses the character class \d to match digits. The + quantifier matches one or more consecutive digits. It finds and displays all numbers present in the input.

import java.util.regex.*;

public class DigitCharacterClass {
    public static void main(String[] args) {
        String input = "Java 123 is released in 2026";
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            System.out.println("Matched: " + matcher.group());
        }
    }
}
Output:
Matched: 123
Matched: 2026

2. Match Letters Using Character Class and Quantifier

This program uses [a-zA-Z] to match English alphabetic characters. The + quantifier matches one or more consecutive letters. It displays each word containing only alphabetic characters.

import java.util.regex.*;

public class LetterCharacterClass {
    public static void main(String[] args) {
        String input = "Java 123 Programming";
        Pattern pattern = Pattern.compile("[a-zA-Z]+");
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            System.out.println("Matched: " + matcher.group());
        }
    }
}
Output:
Matched: Java
Matched: Programming

3. Match One or More Whitespace Characters

This program uses the \s character class to identify whitespace characters. The + quantifier matches one or more consecutive whitespace characters. It displays every whitespace sequence found in the input.

import java.util.regex.*;

public class WhitespaceCharacterClass {
    public static void main(String[] args) {
        String input = "Java   Programming Language";
        Pattern pattern = Pattern.compile("\\s+");
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            System.out.println("Matched whitespace: \"" + matcher.group() + "\"");
        }
    }
}
Output:
Matched whitespace: "   "
Matched whitespace: " "Code language: JavaScript (javascript)

4. Match Specific Characters with a Quantifier

This program uses the character class [abc] to match a, b, or c. The {2,3} quantifier matches between two and three consecutive characters from this class. It displays all matching groups from the input.

import java.util.regex.*;

public class CharacterClassQuantifier {
    public static void main(String[] args) {
        String input = "ab abc abcd";
        Pattern pattern = Pattern.compile("[abc]{2,3}");
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            System.out.println("Matched: " + matcher.group());
        }
    }
}
Output:
Matched: ab
Matched: abc
Matched: abc

References

CodeGPT-small-java
Codebert-base
CodeBERT
Scroll to Top