简体   繁体   English

如何编写仅匹配数字,文本,空格和仅两个特殊字符的正则表达式

[英]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.

相关问题 如何编写仅允许字母,数字和特殊字符(仅中间出现)的正则表达式 - How to Write a Regular Expression that allows only letters, numbers and special characters only i the middle never in the end C#regular表达式,只允许使用字母和数字,但不允许任何特殊字符或空格 - C# regular Expression that allows only alphabets and numbers but not any special characters or spaces 带多个空格和特殊字符的数字的正则表达式? - regular expression for numbers with many spaces and special characters? 如何不允许用户使用正则表达式在 html 中仅在单词的第一位给出特殊字符、数字、空格 - how to not allow user to give special characters, numbers , spaces only in first place of word in html using regex 如何编写正则表达式以排除字符串中的某些特殊字符? - How to write a regular expression for excluding some special characters from string? 如何仅在C#中允许在正则表达式验证中使用有限的特殊字符? - How to allow limited special characters in regular expression validation only in c#? 带引号的文字和特殊字符的正则表达式 - Regular expression for quoted text and special characters 正则表达式只接受9位数字,没有特殊字符,可能只有前导零,最多2位 - Regular Expression accepting only 9 digits, no special characters , may have leading zero's only up to 2 正则表达式只表示数字和字符 - Regex Expression Only Numbers and Characters 特殊字符的正则表达式 - Regular Expression for special characters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM