Home > Enterprise >  REGEX for matching number with two and three numbered patterns together
REGEX for matching number with two and three numbered patterns together

Time:01-17

I have an array of 5 numbers, I'd like to match as long as there are three of the same number and two of the same different number in the array, placement does not matter. Number sequences can be any random string of 5 numbers between 1 - 5. Examples of matches would be: 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.

CodePudding user response:

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.
  •  Tags:  
  • Related