开发者

c# Regex question: only letters, numbers and a dot (2 to 20 chars) allowed

开发者 https://www.devze.com 2022-12-31 02:48 出处:网络
i am wrestling with my regex. I want to allow only letters and numbers and a dot in a username, and 2 to 20 chars long

i am wrestling with my regex. I want to allow only letters and numbers and a dot in a username, and 2 to 20 chars long I thought of something like this

[0-9a-zA-Z]{2,20}

bu开发者_如何学Got then 21 chars is also ok, and that's not what i want


I suggest that you make two checks -- one for length and one for content based on the fact that you probably only want one dot in the name, rather than any number of dots. I'll assume that names like username and user.name are the only formats allowed.

This should get the content( but allows underscores as well):

^\w+(\.\w+)?$

If you don't want underscores, then you would use [0-9a-zA-Z]+ in place of \w+. To explain, it will match any string that consists of one or more word characters, followed by exactly 0 or 1 of a dot followed by one or more word characters. It must also match the beginning and end of the string, i.e., no other characters are allowed in the string.

Then you only need to get the length with a simple length check.


^[0-9a-zA-Z\.]{2,20}$


Try ^[\w\.]{2,20}$ instead.


You need to use start and end of string (^ and $), and escape the .:

^[0-9a-zA-Z\.]{2,20}$
0

精彩评论

暂无评论...
验证码 换一张
取 消