How to check for special characters using regex

前端 未结 3 889
执念已碎
执念已碎 2021-01-02 18:18

NET. I have created a regex validator to check for special characters means I donot want any special characters in username. The following is the code

Regex         


        
相关标签:
3条回答
  • 2021-01-02 18:55

    There's a few things wrong with your expression. First you don't have the start string character ^ and end string character $ at the beginning and end of your expression meaning that it only has to find a match somewhere within your string.

    Second, you're only looking for one character currently. To force a match of all the characters you'll need to use * Here's what it should be:

    Regex objAlphaPattern = new Regex(@"^[a-zA-Z0-9_@.-]*$");
    bool sts = objAlphaPattern.IsMatch(username);
    
    0 讨论(0)
  • 2021-01-02 18:58

    Change your regex to ^[a-zA-Z0-9_@.-]+$. Here ^ denotes the beginning of a string, $ is the end of the string.

    0 讨论(0)
  • 2021-01-02 19:03

    Your pattern checks only if the given string contains any "non-special" character; it does not exclude the unwanted characters. You want to change two things; make it check that the whole string contains only allowed characters, and also make it check for more than one character:

    ^[a-zA-Z0-9_@.-]+$
    

    Added ^ before the pattern to make it start matching at the beginning of the string. Also added +$ after, + to ensure that there is at least one character in the string, and $ to make sure that the string is matched to the end.

    0 讨论(0)
提交回复
热议问题