javascriptregex

Regex - Match repeated character not in sequence


Is there a way to match repeated characters that are not in a sequence?

Let's say I'm looking for at least two 6s in the string.

var string = "61236";

I can only find quantifiers that match either zero or one or characters in a sequence.


Solution

  • Here is a regexp that matches a character that is followed somehwere in the string by the same digit:

    /(.)(?=.*?\1)/
    

    Usage:

    var test = '0612364';
    test.match(/(.)(?=.*?\1)/)[0] // 6
    

    DEMO: https://regex101.com/r/xU1rG4/4

    Here is one that matches it repeated at least 3 times (total of 4+ occurances)

    /(.)(?=(.*?\1){3,})/
    

    DEMO: https://regex101.com/r/xU1rG4/3