const string input = "===== Action: [Action1] State: [State1] by:[user1] at [timestamp1] ===== [Notes1]===== Action: [Action2] State: [State2] by:[user2] at [timestamp2] ===== [Notes2]";
Regex expression = new Regex(@"===== Action: (?<Action>.*?)State:(?<State>.*?)by:(?<userid>.*?)at(?<timestamp>.*?)=====(?<Note>.*?)");
var results = expression.Matches(input);
foreach (Match match in results)
{
Console.WriteLine("UserId:" + match.Groups["userid"].Value);
Console.WriteLine("Action:" + match.Groups["Action"].Value);
Console.WriteLine("State:" + match.Groups["State"].Value);
Console.WriteLine("TimeStamp:" + match.Groups["timestamp"].Value);
Console.WriteLine("Note:" + match.Groups["Note"].Value);
}
除了Note之外,我能够正确解析所有值。我做错了什么想法?
答案 0 :(得分:1)
您忘记在(?======|$)
结束时使用regex
.. (?<Note>.*?)
在您的正则表达式中将匹配所有内容直到结束,这不是您想要的...
所以正则表达式是
===== Action: (?<Action>.*?)State:(?<State>.*?)by:(?<userid>.*?)at(?<timestamp>.*?)=====(?<Note>.*?)(?======|$)
如果输入由换行符
分隔,请使用SinglelineMode
选项
答案 1 :(得分:1)
我的通灵调试意识告诉我,你的正则表达式末尾的.*?
并不贪婪,只会获得0个空格(满足.*?
)。
我认为您可能希望在输入和正则表达式中使用某个符号来确定Note
的结尾应该在哪里