Gur*_*ruC 5 .net c# regex escaping
我正在经历这个问题 C#,Regex.Match整个单词
它说匹配整个单词使用"\ 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;
}
}
Run Code Online (Sandbox Code Playgroud)
但由于%,它失败了.我们有解决方法吗? 可以有其他特殊字符,如'space','(',')'等
如果您有非单词字符,则无法使用\b.您可以使用以下内容
@"(?<=^|\s)" + pattern + @"(?=\s|$)"
Run Code Online (Sandbox Code Playgroud)
编辑:正如蒂姆在评论中提到的那样,你的正则表达式正在失败,因为它们\b之间的边界%与它旁边的空格不匹配,因为它们都是非单词字符.\b仅匹配单词字符和非单词字符之间的边界.
查看更多关于单词边界位置.
说明
@"
(?<= # 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)
)
"
Run Code Online (Sandbox Code Playgroud)