I have an array of 5 numbers, I'd like to match as long as there are * three* of the

`33322`

`24422`

`52225`

`44111`

`54545`

*basically any grouping of 2 and 3 of the same numbers needs to match.Best I've come up with so far:
`^([0-9])\1{2}|([0-9])\1{1}$`

I am not so good with regex, any help would be greatly appreciated.

·
Santiago Trujillo

You can use

```
^(?=[1-5]{5}$)(?=.*(\d)(?:.*\1){2})(?=.*(?!\1)(\d).*\2)\d+$
^(?=.*(\d)(?:.*\1){2})(?=.*(?!\1)(\d).*\2)[1-5]{5}$
```

See the regex demo.

If you want to allow any digits, replace `[1-5]`

with `\d`

.

*Details*:

`^`

- start of string`(?=[1-5]{5}$)`

- there must be five digits from`1`

to`5`

till end of string (this lookahead makes non-matching strings fail quicker)`(?=.*(\d)(?:.*\1){2})`

- a positive lookahead that requires any zero or more chars as many as possible, followed with a digit (captured into Group 1) and then two sequences of any zero or more chars as many as possible and the same digit as captured into Group 1 immediately to the right of the current location`(?=.*(?!\1)(\d).*\2)`

- a positive lookahead that requires any zero or more chars as many as possible, followed with a digit (captured into Group 2) that is not equal to the digit in Group 1, and then any zero or more chars as many as possible and the same digit as captured into Group 2 immediately to the right of the current location`\d+`

- one or more digits`$`

- end of string.

·
Santiago Trujillo
Report

There are many ways to do that. One is to match the following regular expression.

```
^(?=([1-5]).*\1)(?=.+(?!\1)([1-5]).*\2)(?:\1|\2){5}$
```

The idea is as follows.

- use a positive lookahead to match and save to capture group 1 the first digit and require it to appear at least twice;
- use a positive lookahead to match and save to capture group 2 a digit that is different from the digit in capture group 1 and require it to appear at least twice;
- match a five-character string that contains only the digits in the two capture groups.

The regular expression can be broken down as follows.

```
^ # match beginning of string
(?= # begin a positive lookahead
([1-5]) # match a digit 1-5 and save to capture group 1
.* # match zero or more characters
\1 # match the digit in capture group 1
) # end positive lookahead
(?= # begin a positive lookahead
.+ # match one or more characters
(?!\1) # next character is not the digit in capture group 1
([1-5]) # match a digit 1-5 and save to capture group 2
.* # match zero or more characters
\2 # match the digit in capture group 2
) # end positive lookahead
(?:\1|\2){5}$ # match a 5-character string comprised of the digits
# in the two capture groups
```

Here's a second expression that could be used:

```
^(?=([1-5])\1*(?!\1)([1-5])(?:\1*\2){1,2}\1*$).{5}$
```

·
Santiago Trujillo
Report