Skip to main content
 首页 » 编程设计

c#之正则表达式匹配不一致

2024年01月31日26langtianya

我有以下正则表达式:

^(?=.*\d)(?=.*[a-zA-Z])[[!-~]]{6,32}$ 

这应该匹配包含至少 1 个数字、1 个字母字符且长度在 6 到 32 之间的所有字符串(没有空格)。我几乎肯定我的正则表达式是正确的,因为它完美地工作 here .但是,当我在 C# 中使用 Regex.IsMatch 时,它不起作用。

bool isValidInput = Regex.IsMatch(myValue, myRegex) // I expect this to be true but it's false 

除了 C#,我还注意到其他一些测试人员也不喜欢我的正则表达式。喜欢this .我的正则表达式有什么问题?

请您参考如下方法:

This should match all strings (without white spaces) that contain at least 1 digit, 1 alphabetical character, and whose length is between 6 and 32 ...

[[!-~]] 是你的正则表达式的问题,breakdown : (右栏)

相反,我很确定您正在寻找以下内容,\S 匹配非空白字符。

^(?=.*\d)(?=.*[a-zA-Z])\S{6,32}$