Regex类和c# . net中的测试

本文关键字:测试 net 类和 Regex | 更新日期: 2023-09-27 18:09:18

我已经复制了一个在Javascript中工作的RegEx。但当我在c#中运行它时,它返回false。我不确定这是我的代码本身是不正确的,或者如果它是正则表达式。这是我的代码。

bool isValid = true;
string nameInput = "Andreas Johansson";
string emailInput = "email@gmail.com";
string passwordInput = "abcABC123";
string namePattern = @"^[A-z]+(-[A-z]+)*$";
string emailPattern = @"^(['w-'.]+@(['w-]+'.)+['w-]{2,4})?$";
string passwordPattern = @"^(?=.*'d+)(?=.*[a-zA-Z])[0-9a-zA-Z!@#$%]{6,50}$";
Regex nameRegEx = new Regex(namePattern);
Regex emailRegEx = new Regex(emailPattern);
Regex passwordRegEx = new Regex(passwordPattern);
if (model.CreateFullName.Length < 3 || !nameRegEx.IsMatch(nameInput))
                    isValid = false;
if (model.CreateEmail.Length < 3 || !emailRegEx.IsMatch(emailInput))
                    isValid = false;
if (model.CreatePassword.Length < 3 || !passwordRegEx.IsMatch(passwordInput))
                    isValid = false;

感谢输入!

Regex类和c# . net中的测试

您应该从模式定义中删除边界斜杠。它们是javascript而不是。net中的regex对象所必需的。例如:

string namePattern = @"^[A-z]+(-[A-z]+)*$";
string emailPattern = @"^(['w-'.]+@(['w-]+'.)+['w-]{2,4})?$";
string passwordPattern = @"^(?=.*'d+)(?=.*[a-zA-Z])[0-9a-zA-Z!@#$%]{6,50}$";

更新:你在你的编辑中修复了它们。

名称模式仍然不考虑输入中的空格。试着这样做:

^[A-z]+([-'s][A-z]+)*$

还要注意,[A-z]不是匹配字母的正确模式。使用[A-Za-z]来匹配ASCII字母,或使用'p{L}来匹配任何unicode字母。

[A-z]的问题是它也匹配Z之后和a之前的这些字符:

[']^_`