C# 如何使用正则表达式检查特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2279433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check for special characters using regex
提问by Sunil Kumar Sahoo
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 objAlphaPattern = new Regex(@"[[email protected]]");
bool sts = objAlphaPattern.IsMatch(username);
If I provide username as $%^&asghf then the validator gives as invalid data format which is the result I want but If I provide a data [email protected]^&()%^$# then my validator should block the data but my validator allows the data which is wrong
如果我提供用户名 $%^& asghf 那么验证器会提供无效的数据格式,这是我想要的结果但是如果我提供数据 [email protected]^&()%^$# 那么我的验证器应该阻止数据但是我的验证器允许错误的数据
So how to not allow any special characters except a-z A-A 0-9 _ @ .-
那么如何不允许除 az AA 0-9 _ @ 之外的任何特殊字符。-
Thanks Sunil Kumar Sahoo
感谢 Sunil Kumar Sahoo
采纳答案by Spencer Ruport
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(@"^[[email protected]]*$");
bool sts = objAlphaPattern.IsMatch(username);
回答by Anton Gogolev
Change your regex to ^[[email protected]]+$
. Here ^
denotes the beginning of a string, $
is the end of the string.
将您的正则表达式更改为^[[email protected]]+$
. 这里^
表示字符串的开头,是字符串$
的结尾。
回答by Fredrik M?rk
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:
您的模式仅检查给定字符串是否包含任何“非特殊”字符;它不排除不需要的字符。你想改变两件事;让它检查整个字符串是否只包含允许的字符,并检查多个字符:
^[[email protected]]+$
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.
^
在模式之前添加,使其从字符串的开头开始匹配。+$
后面还加上,+
保证字符串中至少有一个字符,并且$
保证字符串匹配到最后。