2

I'm trying to match strings that either:

  • Contains between 9 and 15 numbers (Only numbers)
  • Contains between 6 and 15 numbers+letters (it must contain both, numbers and letters. Only letters is not a valid option).

I have the following regex: \b([0-9]{9,15})|([A-Za-z0-9]{6,15})\b which fails because the second part allows you to have a string with 6 numbers or 6 letters only.

Should be valid:

  • 123456789
  • 12345678Y
  • Y234Y2

Should not be valid:

  • 12345678
  • 123X4
  • ABCDEFGHYJ
Inigo EC
  • 2,178
  • 3
  • 22
  • 31
  • `\b([0-9]{9,15}|[A-Za-z0-9]{6,15})\b`. It should be `\b(a|b)\b`, not `\b(a)|(b)\b` – Wiktor Stribiżew May 06 '22 at 10:44
  • That would not work @WiktorStribiżew, because 12345678 is TRUE and it should be FALSE. The string must either be minimum 9 chars length if it only contain numbers, or min 6 char length if it contains characters – Inigo EC May 06 '22 at 14:46
  • 1
    `^(?:[0-9]{9,15}|(?=[a-zA-Z]*[0-9])(?=[0-9]*[a-zA-Z])[A-Za-z0-9]{6,15})$`? https://regex101.com/r/b4e5n0/1 – Wiktor Stribiżew May 06 '22 at 14:51

1 Answers1

1

You can use

^(?:[0-9]{9,15}|(?=[a-zA-Z]*[0-9])(?=[0-9]*[a-zA-Z])[A-Za-z0-9]{6,15})$

See the regex demo.

Details:

  • ^ - start of string
  • (?: - start of a non-capturing group:
    • [0-9]{9,15} - nine to 15 digits
    • | - or
    • (?=[a-zA-Z]*[0-9])(?=[0-9]*[a-zA-Z])[A-Za-z0-9]{6,15} - six to 15 alphanumeric chars with at least one digit and at least one letter
  • ) - end of the group
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563