2012-07-21 102 views
1

我有例如消息的一些格式:如何在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,以檢查是否有任何提及的格式消息發生。否則我會有一些「原始數據」。 是否有可能使用正則表達式和匹配做這樣的事情?

回答

0

下面是做這件事:

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一開始)

+0

確定,以便適用於我的示例輸入數據,但不適用於此示例:「某些數據?我?消息消息\ r \ n數據的另一部分\ n」 – user36372 2012-07-21 20:27:02

+0

我已修改答案。 – 2012-07-21 20:50:30

+0

再次修改,我發現一些代碼將不匹配的char索引分組到它們的字符串中。 – 2012-07-21 20:59:20

0

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定位點之後立即開始。

0

To match mismatches

string toSearchString = "your string here"; 

Match match = new Regex("*some pattern here*").Match(toSearchString); 

string unmatchedString = toSearchString.Replace(match.Value,""); 

所以,現在你有不匹配的字符串。你可以喝咖啡!