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

1. Match 3 or More Occurrences Using {n,}

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

import java.util.regex.*;

public class NOrMoreOccurrences {
    public static void main(String[] args) {
        String input = "aa 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: aaaa

2. Match 2 or More Digits Using {n,}

This program uses {2,} to match two or more consecutive digits. It matches groups containing at least two digits. Groups containing only one digit are not matched.

import java.util.regex.*;

public class TwoOrMoreDigits {
    public static void main(String[] args) {
        String input = "1 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: 123
Matched: 4567

References

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