python – Regex for username allows for more than one special character
Below is my solution… you can also find it under regex101.com/r/g33uf6/1:
regex = '^[A-Za-z0-9]+([@_\-\.][A-Za-z0-9]*)?$'
The regex starts (^) with allowing 1 or more (+) only characters that belong to any the categories A to Z, a to z, 0 to 9 ([A-Za-z0-9]), in regex terms ^[A-Za-z0-9]+.
The second part allows any number of occurrences (*) in other words zero or more occurrences of characters selected from a given list [@_\-\.] followed by characters from the categories A to Z, a to z, 0 to 9 ([A-Za-z0-9]). In regex terms [@_\-\.][A-Za-z0-9]*.
But we want one or more match of the previous selection, that’s why we add parentheses and the quantifier ? followed with $ marking the position at the end of the line
The regex above includes the following special characters:”_ – . (_\-\.). If you want to include other special characters, add them to the list between the brackets [ ] and make sure to use the escape character \ where necessary, for example the dot symbol requires escaping (\.).
To restrict the total length of the string use the {from, to} quantifier as in {6,15}. Let’s change the regex string to add total length check:
regex = '^([A-Za-z0-9]+([@_\-\.][A-Za-z0-9]*)?){6,15}$'
Note that here parentheses are necessary to inform the {from, to} quantifier whereto apply the quantifier. You can find this version here regex101.com/r/822V7R/1.
regex101.com is a great resource to test and design regex.
Read more here: Source link
