0

对此有一个非常简单的答案,我知道有。但我无法理解它。它是一个控制台应用程序,您输入一个单词“密码”,它会告诉我它是否与我的正则表达式匹配,因为您可以正确收集。

基本上我想知道为什么这不起作用:

static void Main(string[] args)
{
    Regex regularExpression = new Regex("/^[a-z0-9_-]{3,16}$/");

    Console.Write("Enter password: ");
    string password = Console.ReadLine();

    if (Regex.IsMatch(password, regularExpression))
        Console.WriteLine("Input matches regular expression");
    else
        Console.WriteLine("Input DOES NOT match regular expression");

    Console.ReadKey(); 
}

我确定这与Regex.IsMatch无法将字符串转换为 int 的方法有关。

4

2 回答 2

2

因为您使用的是静态方法isMatch并且正在提供一个正则表达式对象,所以它需要一个正则表达式作为字符串,请参阅Regex 类

此外,您不需要 .net 中的正则表达式分隔符。

用这个:

static void Main(string[] args) {
    Regex regularExpression = new Regex(@"^[a-z0-9_-]{3,16}$");

    Console.Write("Enter password: ");
    string password = Console.ReadLine();

    if (regularExpression.IsMatch(password))
        Console.WriteLine("Input matches regular expression");
    else
        Console.WriteLine("Input DOES NOT match regular expression");
    Console.ReadKey(); 
}
于 2013-01-25T12:17:51.190 回答
0
Regex regularExpression = new Regex("/^[a-z0-9_-]{3,16}$/");

/是符号,将它们替换为字符串空 =>@"^[a-z0-9_-]{3,16}$"

于 2013-01-25T12:17:50.290 回答