[英]How to write regular expression that matches only numbers,text,spaces and only two special characters
如何编写仅匹配数字,文本以及仅匹配这两个特殊字符#和-[a-zA-Z0-9#-\\ s] +的任何其他内容的正则表达式
You could a regular expression similar to this 你可以这样一个正则表达式
^(\d|[a-z]|[A-Z]|#|-)*$
Below the code I used for checking the regular expression in c#: 在我用于检查C#中的正则表达式的代码下面:
string input = @"343243-2df---ds#SFD#FD";
string pattern = @"^(\d|[a-z]|[A-Z]|#|-)*$";
Console.WriteLine(Regex.Match(input, pattern).Success);
Console.ReadLine();
Also, for future reference material, you could see this regular expression site: http://www.regular-expressions.info/ 另外,有关将来的参考资料,您可以访问以下正则表达式站点: http : //www.regular-expressions.info/
I believe the following pattern would work in C#: 我相信以下模式可以在C#中使用:
string pattern = @"^[a-zA-Z\d\s#-]*$";
I just tried a couple of test cases in C# interactive: 我只是在C#交互中尝试了几个测试用例:
Regex.Match("", pattern).Success
> true
Regex.Match("asdf 2F#-#-", pattern).Success
> true
Regex.Match("asdf~asdf", pattern).Success
> false
If you don't want to accept an empty string, simply change the * to + in the pattern. 如果您不想接受空字符串,只需将模式中的*更改为+。 Also, you didn't state that you wanted to match whitespace in your question but your example pattern does match whitespace.
另外,您没有声明要与问题中的空格匹配,但是示例模式确实与空白匹配。 If you don't want to match whitespace, remove the \\s.
如果您不想匹配空格,请删除\\ s。
Update : Edited per Rawling's suggestions. 更新 :根据Rawling的建议进行编辑。
尝试这个:
^([a-z]|[A-Z]|[#]|[0-9]|[-])+$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.