string data = @"Title A
Status: Nothing But Net!
Title B
some description on a few lines, there may be empty lines here
some description on a few lines
Status: some other random text
Title C
Can't stop the invisible Man
Credo Quia Absurdium Est
Status: C Status";
string pattern = @"
^(?:Title\s+)
(?<Title>[^\s]+)
(?:[\r\n\s]+)
(?<Description>.*?)
(?:^Status:\s*)
(?<Status>[^\r\n]+)
";
// Ignorepattern whitespace just allows us to comment the pattern over multiple lines.
Regex.Matches(data, pattern, RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace)
.OfType<Match>()
.Select (mt => new
{
Title = mt.Groups["Title"].Value,
Description = mt.Groups["Description"].Value.Trim(),
Status = mt.Groups["Status"].Value.Trim()
})
.ToList() // This is here just to do the display of the output
.ForEach(item => Console.WriteLine ("Title {0}: ({1}) and this description:{3}{2}{3}", item.Title, item.Status, item.Description, Environment.NewLine));
輸出:
Title A: (Nothing But Net!) and this description:
Title B: (some other random text) and this description:
some description on a few lines, there may be empty lines here
some description on a few lines
Title C: (C Status) and this description:
Can't stop the invisible Man
Credo Quia Absurdium Est
[你嘗試過什麼?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – 2012-03-30 14:31:19
是文本以'string'或'string []'或其他結構給出?你能舉一個結果如何的例子嗎? – 2012-03-30 14:36:21
爲了告訴你'真相'我沒有嘗試過任何東西,因爲任務超過了我的正則表達式技能...... – Lincoln 2012-03-30 14:37:03