3

Excuse my ignorance but I really need help with this, I need this regex: [A-Za-z0-9]+\s?[A-Za-z0-9]+ (an username that allows a single whitespace in the middle, but not at the beginning or at the end.), but limiting the total amount of characters to minimum 3 and maximun 30.

I have tried to adapt this answer using negative lookaheads, but so far is not working.

It has to be a regex, it can't use jQuery or anything else.

Community
  • 1
  • 1
David Prieto
  • 2,239
  • 4
  • 32
  • 51

2 Answers2

3

You may use a positive lookahead here:

^(?=.{3,30}$)[A-Za-z0-9]+(?:\s[A-Za-z0-9]+)?$

See the regex demo.

Details:

  • ^ - start of string
  • (?=.{3,30}$) - there can be 3 to 30 chars (other than linebreak, replace the . with [A-Za-z0-9\s] to be more specific)
  • [A-Za-z0-9]+ - 1+ alphanumeric chars
  • (?:\s[A-Za-z0-9]+)? - an optional (1 or 0) occurrences of a
    • \s - whitespace
    • [A-Za-z0-9]+ - 1+ alphanumeric symbols
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
3

You can use:

(?=^[A-Za-z0-9]+\s?[A-Za-z0-9]+$).{3,30}

See a demo on regex101.com. It will match:

username123    # this one
user name 123  # this one not (two spaces!)
user name123   # this one
u sername123   # this one
 username123   # this one not (space in the beginning!)
Jan
  • 42,290
  • 8
  • 54
  • 79