C# 字母数字和特殊字符的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10644318/
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
Regex for alphanumeric and special characters
提问by dotNetNewbie
I need to define a regular expression that accepts Alphanumeric and the following special characters: @#$%&*()-_+][';:?.,!
我需要定义一个接受字母数字和以下特殊字符的正则表达式:@#$%&*()-_+][';:?.,!
I've come up with:
我想出了:
string pattern = @"[a-zA-Z0-9@#$%&*+\-_(),+':;?.,![]\s\/]+$";
But this doesn't seem to be working. Can someone please let me know what is missing?
但这似乎不起作用。有人可以让我知道缺少什么吗?
采纳答案by Ry-
The []in the middle need to be escaped*:
该[]中间需要进行转义*:
\[\]
You also probably want to anchor the start of the string with a ^.
您可能还想使用^.
* Probably just the ]but I like to do both for balance.
* 可能只是]为了平衡,但我喜欢两者都做。
回答by carlosfigueira
Some of those characters need to be escaped (*, +, etc). The easiest way is to simply escape them all:
其中一些字符需要转义(*、+ 等)。最简单的方法是简单地将它们全部转义:
string pattern = @"[a-zA-Z0-9\@\#$\%\&\*\(\)\-\_\+\]\[\'\;\:\?\.\,\!]+$";
回答by Bergi
When defining a character class, you will need to escape the closing bracket ]within, just like "^", "-" and the escaping sequence \itself, which you have done correctly:
定义字符类时,您需要对其中的右括号进行转义],就像“ ^”、“ -”和转义序列\本身一样,您已经正确完成了这些操作:
string pattern = @"[a-zA-Z0-9@#$%&*+\-_(),+':;?.,![\]\s\/]+$";
^ ^ ^

