1

I need a regex to make the validation of an username field. I need to accept just alphanumeric chars and max one space.

What I tried is:

^[a-z0-9]+[ ][a-z0-9]+$

It's working but it doesn't seems the right solution for this problem. Can someone guide me on how to optimize this regex? Thanks.

Keaire
  • 879
  • 1
  • 11
  • 30
  • 3
    Assuming that space shouldn't come at the end or beginning it should be `^(?:[a-z0-9]+ )?[a-z0-9]+$` – revo May 25 '19 at 12:53
  • Seems that is working better, thanks. However yes, since it's an username validation field, the string is going to be trimmed automatically at the beginning and at the end. – Keaire May 25 '19 at 13:02

1 Answers1

0

The following regular expression will do it: ^[a-zA-Z0-9]+ ?[a-zA-Z0-9]+$

You missed only the ? character after the space, what matches between zero and one times.

See full explanation at regex101...

enter image description here

Here you can visualize your regular expressions...

Norbert Incze
  • 351
  • 3
  • 11