2016-04-27 200 views
2

從我讀到的內容來看,如果我想捕獲特定的單詞,我可以使用單詞邊界。正則表達式邊界混淆

我有以下信息

First: 12345Z Apr 16 Something WORD: ABC Notification #1234 Key1 Key2 Key3 Key4 
Second: 12345Z Apr 16 Something WORD: ABC Notification #1234 Key5 Key3 Key6 
Third: 12345Z Apr 16 Something WORD: ABC Notification #1234 Key7 Key6 

我用下面的正則表達式,當我需要匹配Key3 Key4 Key6 Key7

(?<=#\d{4}\s)(\b(Key3|Key4|Key6|Key7)\b) 
+1

你在做什麼,如果它只是不#'後跟隨1234' – rock321987

+0

感謝我剛纔注意到,以及更新將不會與任何關鍵字匹配。感謝這篇文章 – JeremyA1

回答

1

的問題是,你的正則表達式不允許# +4數字與您感興趣的鍵之間的任何內容。您可以通過將可選(?:\s+\w+)*模式添加到後視圖中來輕鬆修復該模式,該模式將匹配0個或更多1個空格和1個以上單詞字符的序列:

(?<=#\d{4}(?:\s+\w+)*)\s*\b(Key3|Key4|Key6|Key7)\b 
      ^^^^^^^^^^^ 

查看regex demo,用C#中的逐字串字面值聲明(或在VB.NET中原樣使用)並與Regex.Matches一起使用。

一個C# demo

var strs = new List<string> { "First: 12345Z Apr 16 Something WORD: ABC Notification #1234 Key1 Key2 Key3 Key4", 
"Second: 12345Z Apr 16 Something WORD: ABC Notification #1234 Key5 Key3 Key6", 
"Third: 12345Z Apr 16 Something WORD: ABC Notification #1234 Key7 Key6"}; 
foreach (var s in strs) { 
    var result = Regex.Matches(s, @"(?<=#\d{4}(?:\s+\w+)*)\s*\b(Key3|Key4|Key6|Key7)\b") 
     .Cast<Match>() 
     .Select(m => m.Value) 
     .ToList(); 
    foreach (var e in result) 
     Console.WriteLine(e); 
} 
1

試試這個

(?:#\d{4}|\G)\s(\b(?:Key3|Key4|Key6|Key7)\b) 

Regex demo它只會匹配Key7

或該

(?:#\d{4}|\G) \b(?:(Key3|Key4|Key6|Key7)|\w+)\b 

Regex demo

說明:
(?: …):非捕獲組sample
\:轉義特殊字符sample
|:輪換/ OR操作數sample
\G:「空白字符」:字符串或上一個匹配的sample
\s終結的開始空格,製表符,換行符,回車,垂直製表sample
(…):捕獲組sample