C# 正则表达式是否要将整个单词与特殊字符匹配不起作用?

C# 正则表达式是否要将整个单词与特殊字符匹配不起作用?,c#,.net,regex,escaping,C#,.net,Regex,Escaping,我正在考虑这个问题 它表示要匹配整个单词,请使用“\b模式\b” 这适用于匹配没有任何特殊字符的整个单词,因为它仅适用于单词字符 我还需要一个表达式来匹配具有特殊字符的单词。我的代码如下 class Program { static void Main(string[] args) { string str = Regex.Escape("Hi temp% dkfsfdf hi"); string pattern = Regex.Escape("

我正在考虑这个问题

它表示要匹配整个单词,请使用“\b模式\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;
    }
}
但它失败了,原因是%。我们有什么解决办法吗?
还可能有其他特殊字符,如“space”、“(“,”)”等

如果模式可以包含正则表达式所特有的字符,请先运行它


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

如果您有非单词字符,则不能使用
\b
。您可以使用以下命令

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

output=Regex.Replace(输出,”(?真,但不是唯一的)他的问题的原因。更确切地说,如果搜索词的开头或结尾是非字母数字字符,则不能使用
\b
,因为定位符在alnum字符和非alnum字符之间匹配。@Yadala-简直太棒了!除了有一个问题外,它几乎就存在了。假设字符串是“嗨,这是堆栈溢出”模式是“这个”,然后它说没有匹配项。这是因为模式中实际字符串后有一个空格。我们如何处理这个问题?理想情况下,应该说找到了一个匹配项!@GuruC如果搜索字符串中有空格,怎么可能仍然是整词搜索?我刚刚在记事本++中验证了这一点,如果我选择整词搜索并搜索嗨,这是stackoverflow"..它不提供任何匹配项。@Yadala-但我希望这样做。即使在记事本++中,如果在搜索中使用option正则表达式,它也会匹配空格。您可以使用visual studio之类的工具来检查行为,效果非常好。@GuruC整个单词都由某个字符绑定,通常开头和结尾都是空白。在继续之前,您需要明确定义整个单词的边界。在记事本++搜索中,您不能同时选择
整个单词
正则表达式
选项。
@"
(?<=        # 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)
)
"
output = Regex.Replace(output, "(?<!\w)-\w+", "")
output = Regex.Replace(output, " -"".*?""", "")