正则表达式在单个foreach循环中一次寻找两种模式

时间:2012-08-26 07:33:40

标签: c# regex

我有一个包含以下内容的文本文件:

+++++ jcguox 4/2/2011 6:19:47 AM

text here

+++++ viveksix 8/24/2012 4:09:17 AM

text again

+++++ viveksix 8/25/2012 11:01:30 AM

----- Vivek Singh 08/25/2012 11:28:12 PM

adding text

+++++ viveksix 8/25/2012 11:02:52 AM

adding more

我想在+++++name date time中选择arraylist类型的所有模式,但条件为:

  • 如果在-----name date time appears之后立即+++++name date time,则此+++++name date time不应添加到arraylist
  • 只有在+++++name date time之后显示文字时,才会将此+++++name date time添加到arraylist

现在我可以使用+++++name date time解析模式-----name date timeRegex.matches

问题是如何在循环中应用如下:

foreach(Match m in Regex.Matches(textfile,@"+++++name date time" + @"-----name date time")
{
    if(after +++++name date time text is there)
        arraylist.Add("+++++name date time");
    else if(after +++++name date time -----name date time is there)
        //do not add in arraylist;
}



output for above case is : 

+++++ jcguox 4/2/2011 6:19:47 AM
+++++ viveksix 8/24/2012 4:09:17 AM
+++++ viveksix 8/25/2012 11:02:52 AM

2 个答案:

答案 0 :(得分:0)

检查一下......

Regex.Match(subjectString, @"\++ (?<author>\w+) (?<date>\d{1,2}/\d{1,2}/\d{4}) (?<time>\d{1,2}:\d{1,2}:\d{1,2} (?:AM|PM))(?!\r\n\r\n-+)")

答案 1 :(得分:0)

试试这个:

string input = @" i have a text file with content something like this:

     +++++ jcguox 4/2/2011 6:19:47 AM

    text here

    +++++ viveksix 8/24/2012 4:09:17 AM

    text again


    +++++ viveksix 8/25/2012 11:01:30 AM

    ----- Vivek Singh 08/25/2012 11:28:12 PM

    adding text


    +++++ viveksix 8/25/2012 11:02:52 AM

    adding more";

        ArrayList al = new ArrayList();

        MatchCollection mc = Regex.Matches(input, @"\++ (?<author>\w+) (?<date>\d{1,2}/\d{1,2}/\d{4}) (?<time>\d{1,2}:\d{1,2}:\d{1,2} (?:AM|PM))(?!\r\n\r\n-+)");
        foreach (Match m in mc)
        {
            string st = m.NextMatch().ToString();
            if (Regex.Match(st, @"\++ (?<author>\w+) (?<date>\d{1,2}/\d{1,2}/\d{4}) (?<time>\d{1,2}:\d{1,2}:\d{1,2} (?:AM|PM))(?!\r\n\r\n-+)").Length > 0)
            {
                al.Add(st);
            }

        }