正则表达式匹配方法无法正常工作

时间:2012-05-03 14:31:45

标签: c# .net windows

我有一个简单地检查文本文件中几个字符串的方法 - 尽管有些字符串没有作为匹配被选中,即使它们存在于文本文档中。我已经包含了在此示例中找不到的有问题的字符串:

static void Main(string[] args)
{
    string str = @"1009 10.32.0.28 03/05/2012 09:11:48 The license expires in 1192 day(s).";
        StreamReader sr = new StreamReader(@"event_history.txt");
        string allRead = sr.ReadToEnd();
        sr.Close();
        string regMatch = str;
        if (Regex.IsMatch(allRead, regMatch))
        {
            Console.WriteLine("found\n");
        }
        else
        {
            Console.WriteLine("not found\n");
        }

        Console.ReadKey();

}

event_history.txt

1009 10.32.0.28 03/05/2012 09:11:48 The license expires in 1192 day(s).

如果我用“测试”替换正则表达式匹配然后将“测试”添加到文本文件中,它会将其作为匹配选择它没有问题:S

4 个答案:

答案 0 :(得分:1)

regMatch = str和str不是正则表达式。你为什么使用RegEx?你应该使用类似于

的东西
".*The license expires in [0-9]* day(s).".

进一步说明,对于IP 10.23.0.28的所有条目:

"1009 10\.32\.0\.28 ..\/..\/.... ..\:..\:.. The license expires in [0-9]* day(s)."

使用文件regex.txt例如:

$ cat regex.txt
1009 10.32.0.28 03/05/2012 09:11:48 The license expires in 1192 day(s).
1009 10.32.0.28 04/05/2012 09:11:48 The license expires in 1192 day(s).
1009 10.32.0.29 04/05/2012 09:11:48 The license expires in 1192 day(s).
1009 10.32.0.30 04/05/2012 09:11:48 The license expires in 1192 day(s).

结果是:

$ grep "1009 10\.32\.0\.28 ..\/..\/.... ..\:..\:.. The license expires in [0-9]* day(s)." regex.txt
1009 10.32.0.28 03/05/2012 09:11:48 The license expires in 1192 day(s).
1009 10.32.0.28 04/05/2012 09:11:48 The license expires in 1192 day(s).
  

如果这是您要检查的字符串(1009,1192天,IP地址和日期   总是静止的。)

使用:

".... 10\.32\.0\.28 04\/05\/2012 ..\:..\:.. The license expires in 1192 day(s)."

答案 1 :(得分:1)

str并不是您要完成的正确的正则表达式。例如,.表示任何字符,s周围的括号是分组,不会被捕获。您实际上只需检查allRead是否包含str,如果这是您要检查的字符串(1009,1192天,IP地址和日期始终是静态的)。

string str = @"1009 10.32.0.28 03/05/2012 09:11:48 The license expires in 1192 day(s).";
StreamReader sr = new StreamReader(@"event_history.txt");
string allRead = sr.ReadToEnd();

if(allRead.Contains(str))
{
    Console.WriteLine("found\n");
}
else
{
    Console.WriteLine("not found\n");
}

如果您正在寻找捕获非静态值的正则表达式,请转到

string str = @"\d+ \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} \d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2} The license expires in \d+ day\(s\)\.";

答案 2 :(得分:0)

您使用Regex.IsMatch作为String.Contains。正则表达式有自己的语法,因此不起作用(通常)。

在您的特定示例中,您需要转义s周围的parantheses,因为正则表达式引擎在它们现在被写入时将不匹配它们,它们是捕获运算符。点也应该被逃脱,虽然具有讽刺意味的正则表达点确实匹配点。所以:

string str = @"1009 10\.32\.0\.28 03/05/2012 09:11:48 The license expires in 1192 day\(s\)\.";

答案 3 :(得分:0)

正则表达式不匹配的原因是因为(和)是正则表达式中的特殊字符。它们代表一个分组,一个您想稍后引用的值。要将它们更改为常规字符,请在它们前面添加\ right。所以你的正则表达式看起来像

@"1009 10.32.0.28 03/05/2012 09:11:48 The license expires in 1192 day\(s\)."
相关问题