正则表达式为字母数字和+字符
我需要一个只允许使用字母数字加上+和 – 字符的正则表达式。
现在我正在使用:
[^\w-]
以下模式将匹配仅包含字母,数字,“+”或“ – ”的字符串,包括“å”或“ö”等国际字符(并且不包括“ \w
”中包含的“_”字符) :
^[-+\p{L}\p{N}]+$
例子:
string pattern = @"^[-+\p{L}\p{N}]+$"; Regex.IsMatch("abc", pattern); // returns true Regex.IsMatch("abc123", pattern); // returns true Regex.IsMatch("abc123+-", pattern); // returns true Regex.IsMatch("abc123+-åäö", pattern); // returns true Regex.IsMatch("abc123_", pattern); // returns false Regex.IsMatch("abc123+-?", pattern); // returns false Regex.IsMatch("abc123+-|", pattern); // returns false
只有在对具有字母数字字符和/或+
/ -
的字符串进行测试时,此正则表达式才会匹配:
^[a-zA-Z0-9\-+]+$
要使用它:
if (Regex.IsMatch(input, @"^[a-zA-Z0-9\-+]+$")) { // String only contains the characters you want. }
试试这个 :
[a-zA-Z0-9+\-]
您必须为单个字符转义 – char: [\w\-+]
,为了更多而转义[\w\-+]+
。
匹配单个,+或字母数字:
[-+a-zA-Z0-9]
匹配任意数量的 – ,+或字母数字:
[-+a-zA-Z0-9]*
匹配只是 – ,+或字母数字的字符串/行:
^[-+a-zA-Z0-9]*$
[A-ZA-Z0-9 \ + \ – ]