Inigo EC
Inigo EC

Reputation: 2328

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

I'm trying to match strings that either:

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:

Should not be valid:

Upvotes: 2

Views: 423

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

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.

Upvotes: 1

Related Questions