我有一些格式为:
T01: 警告: 标签1: 消息
T23: 标签2: 消息2
的日志字符串,我试图从中提取T
号码,并检测是否存在警告:
,然后在一个正则表达式中获取标签和消息的文本。但是"警告:"这个可选要求让我困惑了。
private const string RegexExpression = @"^T(?<Number>\d+): (?<Warning>Warning:)? (?<Tag>[^:]+): (?<Message>.*)";
private const string Message = "blar blar blar: some messsage";
//this test works
[TestMethod]
public void RegExMatchByTwoNamedGroupsWarningTest()
{
var rex = new Regex(RegexExpression);
const string wholePacket = "T12: Warning: logtag: " + Message;
var match = rex.Match(wholePacket);
Assert.IsTrue(match.Groups["Warning"].Success); //warning is present
Assert.IsTrue(match.Success);
Assert.IsTrue(match.Groups["Number"].Success);
Assert.AreEqual("12", match.Groups["Number"].Value);
Assert.IsTrue(match.Groups["Tag"].Success);
Assert.AreEqual("logtag", match.Groups["Tag"].Value);
Assert.IsTrue(match.Groups["Message"].Success);
Assert.AreEqual(Message, match.Groups["Message"].Value);
}
[TestMethod]
public void RegExMatchByTwoNamedGroupsNoWarningTest()
{
var rex = new Regex(RegexExpression);
const string wholePacket = "T12: logtag: " + Message;
var match = rex.Match(wholePacket);
Assert.IsFalse(match.Groups["Warning"].Success); //warning is missing
Assert.IsTrue(match.Success); //fails
Assert.IsTrue(match.Groups["Number"].Success); //fails
Assert.AreEqual("12", match.Groups["Number"].Value);
Assert.IsTrue(match.Groups["Tag"].Success); //fails
Assert.AreEqual("logtag", match.Groups["Tag"].Value);
Assert.IsTrue(match.Groups["Message"].Success); //fails
Assert.AreEqual(Message, match.Groups["Message"].Value);
}