-2
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 之外的所有值。任何想法我做错了什么?

4

2 回答 2

1

您忘记在..(?======|$)末尾使用您的正则表达式将匹配所有内容直到结束,这不是您想要的..regex(?<Note>.*?)

所以正则表达式是

===== Action: (?<Action>.*?)State:(?<State>.*?)by:(?<userid>.*?)at(?<timestamp>.*?)=====(?<Note>.*?)(?======|$)

SinglelineMode如果输入由换行符分隔,则使用选项

于 2013-02-27T16:57:33.773 回答
1

我的心理调试感觉告诉我,.*?你的正则表达式末尾的 不是贪婪的,只会拾取 0 个空格(满足.*?)。

我认为您可能希望在输入和正则表达式中使用一些符号来确定Note应该在哪里结束

于 2013-02-27T16:58:01.860 回答