Karl Pokus
Karl Pokus

Reputation: 810

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.

Upvotes: 5

Views: 1458

Answers (5)

AbsoluteBeginner
AbsoluteBeginner

Reputation: 2255

You can remove the ? after .* since the .* already matches zero or more characters.

(.)(?=.*\1)

var test = "0612364";
console.log(
  test.match(/(.)(?=.*\1)/)[0]
);

Upvotes: 0

Tibos
Tibos

Reputation: 27823

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

Upvotes: 7

Maciek
Maciek

Reputation: 158

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

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

Upvotes: 0

Tom
Tom

Reputation: 16188

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

Upvotes: 0

Toto
Toto

Reputation: 91385

Have a try with this regex:

/(.).*?\1/

Upvotes: 3

Related Questions