At least one number with existing regex

Viewed 64

My conditions ...

  1. Alpha-Numeric value
  2. Only one space or hyphen is allowed
  3. Must contain at least one number
  4. Cannot start or end with space or hyphen
  5. Minimum 2 characters, maximum 16 characters excluding space/hyphen

As of now I prepared the regex

^(?=.{2,16}$)([a-zA-Z\d]+)([\s^\-]|[\-^\s]|[a-zA-Z\d]*)([a-z[A-Z\d]+)

Its only missing 3rd point.

Test strings Valid

"test one"
"test 2two"
"test3 three222"
"3test-4four"

Invalid

"-test"
"test-d f"
1 Answers

You may use this regex with 2 lookahead conditions:

^(?=(?:[a-zA-Z\d][ -]?){2,16}$)(?=[^\d\n]*\d)[a-zA-Z\d]+(?:[ -][a-zA-Z\d]+)?$

RegEx Demo

PS: Note that test one is an invalid string as it doesn't have any digit.

RegEx Details:

  • ^: Start
  • (?=(?:[a-zA-Z\d][ -]?){2,16}$): Positive Lookahead to make sure we have 2 to 16 length of alphanumeric characters
  • (?=\D*\d): Positive Lookahead to make sure we have at least one digit
  • [a-zA-Z\d]+(?:[ -][a-zA-Z\d]+)?: Match any test that starts with alphanumeric, optionally followed by a single space or hyphen and ends with alphanumeric
  • $: End
Related