简体   繁体   中英

Regex matches but shouldn't

This is my code that checks if there are only alphanumeric characters filled in, but when i enter something like adasd@#$ it still matches and i have no idea why. Any idea how to fix this?

Match Match = Regex.Match(value.ToString(), "[0-9a-zA-Z]");
                if (Match.Success)
                {
                    return true;
                }
                else
                {
                    return false;
                }   

What you have matches any string that contains one letter or number somewhere in it.

You need to add anchors to the beginning and end of the string ( ^ and $ ), as well as a + to allow for more than one character:

"^[0-9a-zA-Z]+$"

This means "the entire string must be made of letters and numbers".

The + also requires that there is at least one character in the string. This is probably a good thing, but if you want to match empty strings, as well, you can change it to * .

Your regex [0-9a-zA-Z] checks for any alphanumeric character in the input string. Since it finds a, d, a, s, d in your input string, it returns true.
What you need to do is place start and end enchors in your regex. New regex would look like this:

^[0-9a-zA-Z]+$

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