我有一个正则表达式模式,该模式应允许所有字母数字字符以及-_.和空格

"[A-Za-z0-9-_. ]+"

我正在尝试使用Regex.IsMatch对此正则表达式验证字符串,但它返回true。为什么?

string pattern = "[A-Za-z0-9-_. ]+";
string input = "rtgfd&**((&";
bool isMatch = Regex.IsMatch(input, pattern);
// isMatch is true, why?

最佳答案

之所以匹配,是因为您的字符串在[A-Za-z0-9-_. ]集中确实包含一个或多个字符。如果您只想要这样,请将您的模式更改为此:

string pattern = "^[A-Za-z0-9-_. ]+$";


它将强制模式从字符串的开头到结尾匹配。

关于c# - Regex.IsMatch在不应该的情况下返回true,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21859753/

10-12 17:27