简体   繁体   中英

regex not detecting space in username textbox

I have a asp:textbox taking a Username that is part of a Signup form for a new user account.

Obviously I don't want the user to sign up using a space as a name so I have this regular expression which should keep the valid entry to ASCII characters between 3 and 16 in length with NO SPACES.

but the no spaces doesn't work in practice. it works in Regex editors and checkers but not my aspx page.

Any suggestions?

^([a-zA-Z0-9!@#$%^&*()-_=+;:'"|~`<>?/{}]{3,16})$|\s

many thanks

^([a-zA-Z0-9!@#$%^&*()-_=+;:'"|~`?/{}]{3,16})$

Your current regex says: "I match a string if the string is made of these characters and is 3 to 16 characters in length OR if it contains a whitespace character."

So, if you don't want it to match spaces, remove |\\s (ie the 'or' operator and the whitespace pattern) from the regex.

It seems your having trouble understanding what dtb is trying to say. Let me break-down the regex for you and you will see what he is saying:

^ - matches the beginning of the input string
( - begins a capture group, in your case useless and can be removed along with the closing ) just before the $
[ - begins a group of characters
a-zA-Z0-9!@#$%^&*()-_=+;:'"|~`?/{} - defines all the characters allowed, NOTICE there is no space character so spaces will not count
] - ends the group of characters
{3,16} - says that the preceding character(or group of characters in this case) must occur between 3 and 16 times
) - closes the capture group, again can be removed with the open (
$ - matches the end of the input string

This is where your expression goes awry...

| - says that the preceeding match expression (this is the $ which is the end of input) OR the following must be true, but not necessarily both
\s - matches a space or tab anywhere in the input string

So (if I'm reading this correctly) your regex states:

"I match a string if the string starts with ascii characters and is 3 to 16 characters in length before it finds either the end of the string or some whitespace (tab or space)."

To fix it, remove the '|\\s' from the end of your expression and just use the following:

^([a-zA-Z0-9!@#$%^&*()-_=+;:'"|~`<>?/{}]{3,16})$

A simpler answer would be:

^([^\s]{3,16})$

which means "the whole string must consist of three to sixteen repeats of anything other than whitespace."

That will allow accented characters as well, but that's probably something you'll need to accept anyway.

更简单的是

^\S{3,16}$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM