正则表达式匹配整个单词与特殊字符不工作?

问题描述:

我所经历的这个问题 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; 
    } 
} 

但它由于%失败。我们有任何解决方法吗? 可以有其它特殊字符,如“空间”,“(”,“)”等

的这个问题的答案可以在这里找到

Regex expression to match whole word

感谢您的答案!

如果图案可以包含特殊到正则表达式的字符,通过Regex.Escape第一运行它。

这是你做的,但是做不是转义字符串,你搜索 - 你不需要。

+0

是的,但不是他的问题(仅)的原因。 –

如果您有非单词字符,则不能使用\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”,它不会给出任何匹配。 –

output = Regex.Replace(output, "(?<!\w)-\w+", "") 
output = Regex.Replace(output, " -"".*?""", "")