RegEx possible optimizations and shorthand tricks

I attempted to create a RegEx that matched usernames with 1 to 20 characters and no more than one space (optional though). And by trial and error obtained this chunky RegEx:

[0-9A-Za-z]{3,20} ?[0-9A-Za-z]{1,20}

How can I optimize this RegEx to be shorter and generally better?

Answer

Use a negative lookahead that says the input string cannot have two spaces:

^(?!S* S* )[0-9A-Za-z ]{1,20}$

Regex Demo

Note: Your regex does not allow space in the first 3 positions, but this one does. I am going just by your verbal description, not your regex. (Your regex would also allow more than 20 characters in the name, as many as 41, and that’s why I ignored it).