2011-06-17 23 views
1

我們有一個客戶端應用程序,用戶想要搜索指定文本的「筆記」字段。這些字段可以用HTML或明文格式化。我們最近做出的改變之一是僅支持「全字」匹配。使用\b,我們做到了這一點。模式:

"\b(?:match)\b" <-- works 

新的一天,新的問題:他們想要找到的值之一是一個數字,後面跟着一個百分號。 (%)但是,模式不匹配。經過一番研究後,我能夠確定,對於位置n的一個字符被視爲一個字末端邊界,\b斷言位置n - 1上的字符必須是單詞字符。但是,%不是一個單詞字符,所以匹配失敗。

"\b(?:7.0%)\b" <-- fails 

我改變了這種匹配\W,和它的作品,但這種的缺點是必須始終有匹配模式下另一個角色。

"\b(?:7.0%)\W" <-- works, mostly 

所以,我想知道的是,我可以使用下面的模式,有它結束的字符串匹配匹配嗎?

"\b(?:7.0%)(\W|$)" <-- ?? 

我測試,它出現工作,但有什麼,是要咬我的道路?

編輯:

這裏有一個快速測試工具,演示不同的行爲,其中包括從代理-J答案:

 List<string> testInputs = new List<string>(); 

     testInputs.Add("This string contains 7.0% embedded within it."); 
     testInputs.Add("In this string, 7.0%\nis at the end of a line."); 
     testInputs.Add("7.0% starts this string."); 
     testInputs.Add("This string ends with 7.0%"); 

     List<string> testPatterns = new List<string>(); 
     testPatterns.Add(@"\b(?:7.0%)\b"); 
     testPatterns.Add(@"\b(?:7.0%)\W"); 
     testPatterns.Add(@"\b(?:7.0%)(\W|$)"); 
     testPatterns.Add(@"\b(?:7.0%)(?!\w)"); 

     foreach (var patt in testPatterns) 
     { 
      Console.WriteLine(string.Format("Testing pattern '{0}'", patt)); 

      foreach (var input in testInputs) 
      { 
       Console.WriteLine(string.Format("Input '{0}'; result: {1}", input, Regex.IsMatch(input, patt))); 
      } 

      Console.WriteLine(); 
     } 

輸出:

Testing pattern '\b(?:7.0%)\b' 
Input 'This string contains 7.0% embedded within it.'; result: False 
Input 'In this string, 7.0% 
is at the end of a line.'; result: False 
Input '7.0% starts this string.'; result: False 
Input 'This string ends with 7.0%'; result: False 

Testing pattern '\b(?:7.0%)\W' 
Input 'This string contains 7.0% embedded within it.'; result: True 
Input 'In this string, 7.0% 
is at the end of a line.'; result: True 
Input '7.0% starts this string.'; result: True 
Input 'This string ends with 7.0%'; result: False 

Testing pattern '\b(?:7.0%)(\W|$)' 
Input 'This string contains 7.0% embedded within it.'; result: True 
Input 'In this string, 7.0% 
is at the end of a line.'; result: True 
Input '7.0% starts this string.'; result: True 
Input 'This string ends with 7.0%'; result: True 

Testing pattern '\b(?:7.0%)(?!\w)' 
Input 'This string contains 7.0% embedded within it.'; result: True 
Input 'In this string, 7.0% 
is at the end of a line.'; result: True 
Input '7.0% starts this string.'; result: True 
Input 'This string ends with 7.0%'; result: True 
+0

測試字符串是否會包含換行符,如果是,您希望'$'匹配那些換行符還是整個字符串的結尾? –

+0

它可能包含換行符,但我不確定它確實很重要它匹配 - 我只是想知道該字段包含搜索文本,作爲一個整體詞。 – GalacticCowboy

回答

3

你是一個正確的軌道。當有字符時,你的表達\b(?:7.0%)(\W|$)將匹配7.0%後面的字符。相反,請考慮使用負面預測(?!\w),這樣額外的字符不是您匹配的一部分。

\b(?:7.0%)(?!\w) 

如果字符串以7.0%結束,它會匹配,如果字符串7.0%.結束,它將匹配7.0%。無論您的正則表達式選項是單線還是多線,它都會匹配。

+0

這很酷,我沒有想到這一點。 – GalacticCowboy

相關問題