0

我有一个带有重复模式的字符串

MM/DD/YYYY (FirstName LastName) Status Update: blah blah blah blah

例如

string test = "11/01/2011 (Joe Bob) Status Update: Joe is the collest guy on earfth 08/07/2010 (Rach Mcadam) Status Update: whatever I dont care 06/28/2009 (Some Guy) Status Update: More junk and note how I end there's not gonna be another date after me"

如何分组匹配,以便为每场匹配更新日期、名称和状态?

我试过了

        string datePattern = "\\d{1,2}/\\d{1,2}/\\d{0,4}";
        string personPattern = "\\(\\w*\\)";
        Regex regex = new Regex("(" + datePattern + ") (" + personPattern + ") (.*)");
        MatchCollection matches = regex.Matches(test);
        foreach (Match match in matches)
        {
            Console.WriteLine("##Match Found##");
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine(match.Groups[0]);//full text
            Console.WriteLine("");
            Console.WriteLine(match.Groups[1]);//date only
            Console.WriteLine("");
            Console.WriteLine(match.Groups[2]);//person
            Console.WriteLine("");
            Console.WriteLine(match.Groups[3]);//note
        }

在这一点上它什么也没有拉回来。

4

1 回答 1

3

空格不包含在 中\w,因此\w*不会匹配Joe Bob。尝试更改personPattern"\\([ \\w]*\\)".

看起来您的正则表达式也太贪心了,因为.*末尾的 将匹配字符串的其余部分,而不是在下一个日期停止。尝试将您的正则表达式更改为以下内容:

Regex regex = new Regex("(" + datePattern + ") (" + personPattern + ") (.*?(?=$|" + datePattern + "))");
于 2012-08-06T21:42:13.960 回答