正则表达式匹配整个单词与特殊字符不工作?
我所经历的这个问题 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;
}
}
但它由于%失败。我们有任何解决方法吗? 可以有其它特殊字符,如“空间”,“(”,“)”等
如果您有非单词字符,则不能使用\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)
)
"
更确切地说,如果您的非字母数字字符是搜索词的开头或结尾,则不能使用'\ b',因为该锚点在alnum字符和非alnum字符之间匹配。 –
@Yadala - 简直太棒了!它几乎在那里,除了它有一个问题。假设字符串是“你好,这是stackoverflow”和模式是“这个”,那么它说没有匹配。发生这种情况是因为模式中实际字符串之后的空白空间。我们该如何处理?理想情况下,应该说找到了一场比赛! – GuruC
@GuruC如果你的搜索字符串中有空白,它怎么还是全文搜索?我只是在Notepad ++中验证了这一点,如果我选择整词搜索并在“Hi this stackoverflow”中搜索“this”,它不会给出任何匹配。 –
output = Regex.Replace(output, "(?<!\w)-\w+", "")
output = Regex.Replace(output, " -"".*?""", "")
是的,但不是他的问题(仅)的原因。 –