Home > OS >  Regex to match a string that contains n occurrences of a particular character (anywhere in string)
Regex to match a string that contains n occurrences of a particular character (anywhere in string)

Time:10-29

I'm trying to construct a regex that will match a string, when there are n or more occurrences of a particular character (anywhere in string).

E.g. the character is /, and n=2

Would give:

test -> false
/test -> false
/test/test -> true
/test/test/test -> true

How best to do this?

CodePudding user response:

You can use backreference:

(/).*\1.*\1

CodePudding user response:

Or you can use capturing groups:

public static void main(final String args[]) throws Exception
{
    final String input = "/test/test/test";

    final String toCount = "/";
    final int n = 2;

    System.out.println("Looking for ".concat(n   "x: \"".concat(toCount).concat("\"")));
    System.out.println("RESULT for \"".concat(input).concat("\": ")   filterChars(input, toCount, n));
}

public static boolean filterChars(final String s, final String toCount, final int n)
{
    // Oh boy, this is the best... string concatenation to create regex patterns... what could go wrong?
    // Please... think of the children
    final Pattern p = Pattern.compile("("   toCount   ")");
    final Matcher m = p.matcher(s);

    int count = 0;
    while (m.find())
    {
        count  ;
    }

    return (n <= count);
}

CodePudding user response:

You can use a capturing lookahead:

/^(?=(\/)(?:.*\1){1,}).*/gm

Demo

  • Related