3

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.

Thanks.

2
  • Can they be in sequence as well?
    – user557597
    Commented Jan 16, 2014 at 16:29
  • Yes. But does not have to.
    – Karl Pokus
    Commented Jan 17, 2014 at 8:57

4 Answers 4

7

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

8
  • 1
    Maybe add a lazy qualifier so that the .* doesn't match all the way to the right before looking for a backreference match: /(\d)(?=.*?\1)/ Commented Jan 16, 2014 at 16:22
  • @MikeSamuel Added, thanks. I can't seem to add a maximum amount of occurances to the regex. Does anyone have any ideas? I tried [^\1] instead of ., but that is the character 1, tried {3,5}, but that just matches the \d with ..
    – Tibos
    Commented Jan 16, 2014 at 16:28
  • to match a maximum, you need to ensure that the .*? does not match \1: (?:(?!=\1).)*? Commented Jan 16, 2014 at 16:33
  • Awesome! It works. Thank you! Damn you guys are fast.
    – Karl Pokus
    Commented Jan 16, 2014 at 16:37
  • @MikeSamuel I tried that in the meantime, but it doesn't seem to work: regex101.com/r/iL2dQ1 Perhaps i made a stupid mistake?
    – Tibos
    Commented Jan 16, 2014 at 16:41
3

Have a try with this regex:

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

Match 6 and anything up until another 6

!!"61236".match("6.*6")
// returns true

Match 6 and anything up until another the same as the first group (which is a 6)

!!"61236".match(/(6).*\1/)
// returns true
2
  • What are those !! doing in the beginning? Is that js?
    – Karl Pokus
    Commented Jan 16, 2014 at 16:39
  • 1
    @KarlPokus it converts the value returned by match to a boolean. If a match is found, the resulting array gets converted to true, otherwise null gets converted to false.
    – Tibos
    Commented Jan 16, 2014 at 16:44
0

Characters that are not in sequence and appear more than once:

/(.)(.+\1)+/
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.