Matches exactly n occurrences of the preceding character or group ({n})

1. Match Exactly 3 Occurrences Using {n}

This program demonstrates the {n} quantifier in Java regular expressions. The {n} matches exactly n occurrences of the preceding character or group. Here, {3} matches exactly three consecutive occurrences of the character a.

import java.util.regex.*;

public class ExactOccurrences {
    public static void main(String[] args) {
        String input = "aaa aaaa aa";
        Pattern pattern = Pattern.compile("a{3}");
        Matcher matcher = pattern.matcher(input);

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

2. Match Exactly 2 Digits Using {n}

This program uses {2} to match exactly two consecutive digits. The pattern matches only groups containing two digits at a time. It does not match a single digit by itself.

import java.util.regex.*;

public class ExactDigitOccurrences {
    public static void main(String[] args) {
        String input = "12 123 4567";
        Pattern pattern = Pattern.compile("\\d{2}");
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            System.out.println("Matched: " + matcher.group());
        }
    }
}
Output:
Matched: 12
Matched: 12
Matched: 45
Matched: 67

References

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