我有我的正则表达式如下问题,我想它匹配毛虫字符串中的"这是一个毛毛虫的牙齿",但它相匹配的猫.我该怎么改变它?
List<string> women = new List<string>()
{
"cat","caterpillar","tooth"
};
Regex rgx = new Regex(string.Join("|",women.ToArray()));
MatchCollection mCol = rgx.Matches("This is a caterpillar s tooth");
foreach (Match m in mCol)
{
//Displays 'cat' and 'tooth' - instead of 'caterpillar' and 'tooth'
Console.WriteLine(m);
}
Run Code Online (Sandbox Code Playgroud)
SLa*_*aks 13
你需要一个表格的正则表达式\b(abc|def)\b.
\b是一个单词分隔符.
此外,您需要呼叫Regex.Escape每个单词.
例如:
new Regex(@"\b(" + string.Join("|", women.Select(Regex.Escape).ToArray()) + @"\b)");
Run Code Online (Sandbox Code Playgroud)