Matches between n and m occurrences of the preceding character or group ({n,m})

1. Match Between 2 and 4 Occurrences Using {n,m}

This program demonstrates the {n,m} quantifier in Java regular expressions. The {n,m} matches at least n and at most m occurrences of the preceding character or group. Here, {2,4} matches between two and four consecutive a characters.

import java.util.regex.*;

public class RangeOccurrences {
    public static void main(String[] args) {
        String input = "a aa aaa aaaa aaaaa";
        Pattern pattern = Pattern.compile("a{2,4}");
        Matcher matcher = pattern.matcher(input);

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

2. Match Between 2 and 3 Digits Using {n,m}

This program uses {2,3} to match groups containing two or three consecutive digits. It does not match a single digit because the minimum is two. It matches a maximum of three digits in each group.

import java.util.regex.*;

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

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

References

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