Home > Net >  How to ensure that a string contains numbers and letters by using RegEx
How to ensure that a string contains numbers and letters by using RegEx

Time:05-08

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

CodePudding user response:

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