如何在c#regex中捕获匹配和不匹配?
问题描述:
我有例如消息的一些格式:如何在c#regex中捕获匹配和不匹配?
"?I?Message message message\r\n"
现在我想通过正则表达式使用命名组捕捉到了这个信息:
(?<Message>\?(?<Type>\S)\?(?<Text>[\S\s]+(\r\n)+))
但我想有这确实也是所有字符串不符合此消息格式。例如:
"Some data?I?Message message\r\nAnother part of data\n"
会给我3场比赛:??
- “一些数据”
- 我留言信息\ r \ n
- “数据\ n的另一部分”
我可以检查消息组是否具有成功字段设置为true,以检查是否有任何提及的格式消息发生。否则我会有一些“原始数据”。 是否有可能使用正则表达式和匹配做这样的事情?
答
下面是做这件事:
var str = "Some data?I?Message message\r\nAnother part of data\n";
var unmatchedCharIndices = Enumerable.Range(0, str.Length);
foreach (Match match in Regex.Matches(str, @"(?<Message>\?(?<Type>\S)\?(?<Text>[\S\s]+(\r\n)+))"))
{
unmatchedCharIndices = unmatchedCharIndices.Except(Enumerable.Range(match.Index, match.Length));
//do other stuff with match
}
var unmatchedStrings = unmatchedCharIndices
.Select((n, i) => new { n, i })
.GroupBy(x => x.n - x.i) //this line will group consecutive nums in the seq
.Select(x => str.Substring(x.First().n, x.Count()));
foreach (var unmatchedString in unmatchedStrings)
{
//do something with non-match text
}
(unmatchedStrings
感谢代码Getting last x consecutive items with LINQ一开始)
答
从Regex.Match
结果对象是Match
类型。其Success
属性显示如果正则表达式整体匹配。
但也有一个Groups
属性,您可以使用它来查看个人,命名或不是捕获组。如果一个命名捕获失败,那么该组的Success
属性将是错误的。
因此,与
var m = Regex.Match("Fubar", "(?<x>Z)?.*");
然后
m.Success
是真实的,但
m.Groups['Z'].Success
是假的。
随着Regex.Matches
正则表达式可以匹配多次,每个匹配将返回MatchCollection
单个Match
对象。 但正则表达式将默认跳过不匹配,因此输入部分:
Regex.Matches("ZaZ", "Z")
将返回两场比赛的集合,但没有为“a
”。您可以强制下一场比赛在\G
定位点之后立即开始。
答
To match mismatches
string toSearchString = "your string here";
Match match = new Regex("*some pattern here*").Match(toSearchString);
string unmatchedString = toSearchString.Replace(match.Value,"");
所以,现在你有不匹配的字符串。你可以喝咖啡!
确定,以便适用于我的示例输入数据,但不适用于此示例:“某些数据?我?消息消息\ r \ n数据的另一部分\ n” – user36372 2012-07-21 20:27:02
我已修改答案。 – 2012-07-21 20:50:30
再次修改,我发现一些代码将不匹配的char索引分组到它们的字符串中。 – 2012-07-21 20:59:20