I am not a regex ninja. I’ve been tweaking this for an hour, and I’m sure someone on SO can do it more effectively.
This is a regex for a username with some slightly peculiar requirements (to accomodate legacy usernames).
Rules:
- length: 24 charaters maximum, 3 characters minimum
- must not start or end with a space
- any number of the following (up to the max field lenght of 24):
- 0-9
- A-Z
- a-z
- . (dot)
- ‘ ‘ (space)
- zero or one of each from following set:
- @ (at)
- _ (underscore)
- – (hyphen)
- ‘ (apostrophy)
Here’s what I have so far:
^[^ ](?=[A-Za-z0-9. @_\-]{1,24}$)[a-zA-Z0-9_. ]*\.?[a-zA-Z0-9_]*[^ ]$
but it is not quite right. I’m not sure how to escape the ‘ (apostrophe)
also, should I use another lookahead for the characters allowed zero or one times?
Thanks.
Update:
Note that target is the .Net 4.0 regex libraries with C#
This would be a regex solution, decide on your own if this is readable/usable/maintainable for you.
See it here on Regexr
(?!^.*?([@'_-]).*\1.*$)is a negative lookahead, if one of the characters you named is found it is put into capturing group 1 and to ensure this is not repeating using the backreference\1.^(?! )is a negative lookahead to ensure there is no space after the start of the string.[\w. @'-]{3,24}The characters you allow at least 3 at most 24 of them(?<! )$is a negative lookbehind to ensure there is no space before the end of the string.