How to match a single space total not just a single space using regular expressions

Will allow atmost one space in between.

^[a-zA-Z0-9]+\s?[a-zA-Z0-9]+$

Will allow exactly one space in between

^[a-zA-Z0-9]+\s[a-zA-Z0-9]+$

EDIT1:

Above solutions does not accept single character strings.

The below solutions also matches single character strings

^[a-zA-Z0-9]+([ ][a-zA-Z0-9]+)?$


First clean the username by trimming leading and trailing whitespace.

^[a-z0-9]+(?: [a-z0-9]+)?$

Tags:

Regex