我有一个包含以下内容的文本文件:
+++++ 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 time
和Regex.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
答案 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);
}
}