2011-11-24 122 views
6

我所經歷的這個問題 C#, Regex.Match whole words正則表達式匹配整個單詞與特殊字符不工作?

它說的全字匹配使用「\ bpattern \ B」 這工作正常全字匹配,沒有任何特殊字符,因爲它是爲隻字字符!

我需要一個表達式來匹配帶有特殊字符的單詞。我的代碼如下

class Program 
{ 
    static void Main(string[] args) 
    { 
     string str = Regex.Escape("Hi temp% dkfsfdf hi"); 
     string pattern = Regex.Escape("temp%"); 
     var matches = Regex.Matches(str, "\\b" + pattern + "\\b" , RegexOptions.IgnoreCase); 
     int count = matches.Count; 
    } 
} 

但它由於%失敗。我們有任何解決方法嗎? 可以有其它特殊字符,如「空間」,「(」,「)」等

回答

3

如果圖案可以包含特殊到正則表達式的字符,通過Regex.Escape第一運行它。

這是你做的,但是做不是轉義字符串,你搜索 - 你不需要。

+0

是的,但不是他的問題(僅)的原因。 –

5

如果您有非單詞字符,則不能使用\b。您可以使用以下

@"(?<=^|\s)" + pattern + @"(?=\s|$)" 

編輯:蒂姆在評論中提到,你的正則表達式正是失敗,因爲\b未能%與白色空間之間的邊界匹配旁邊,因爲他們兩個都是非字符。 \b僅匹配單詞字符和非單詞字符之間的邊界。

查看更多關於單詞界限here

說明

@" 
(?<=  # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) 
       # Match either the regular expression below (attempting the next alternative only if this one fails) 
    ^   # Assert position at the beginning of the string 
    |   # Or match regular expression number 2 below (the entire group fails if this one fails to match) 
     \s   # Match a single character that is a 「whitespace character」 (spaces, tabs, and line breaks) 
) 
temp%  # Match the characters 「temp%」 literally 
(?=   # Assert that the regex below can be matched, starting at this position (positive lookahead) 
       # Match either the regular expression below (attempting the next alternative only if this one fails) 
     \s   # Match a single character that is a 「whitespace character」 (spaces, tabs, and line breaks) 
    |   # Or match regular expression number 2 below (the entire group fails if this one fails to match) 
     $   # Assert position at the end of the string (or before the line break at the end of the string, if any) 
) 
" 
+1

更確切地說,如果您的非字母數字字符是搜索詞的開頭或結尾,則不能使用'\ b',因爲該錨點在alnum字符和非alnum字符之間匹配。 –

+0

@Yadala - 簡直太棒了!它幾乎在那裏,除了它有一個問題。假設字符串是「你好,這是stackoverflow」和模式是「這個」,那麼它說沒有匹配。發生這種情況是因爲模式中實際字符串之後的空白空間。我們該如何處理?理想情況下,應該說找到了一場比賽! – GuruC

+0

@GuruC如果你的搜索字符串中有空白,它怎麼還是全文搜索?我只是在Notepad ++中驗證了這一點,如果我選擇整詞搜索並在「Hi this stackoverflow」中搜索「this」,它不會給出任何匹配。 –

1
output = Regex.Replace(output, "(?<!\w)-\w+", "") 
output = Regex.Replace(output, " -"".*?""", "") 
相關問題