我的正则表达式存在以下问题,我希望它能匹配字符串中的 caterpillar “这是卡特彼勒的牙齿”但它匹配猫。我怎样才能改变它?
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);
}
答案 0 :(得分:13)
您需要\b(abc|def)\b
形式的正则表达式
\b
是一个单词分隔符。
此外,您需要在每个单词上调用Regex.Escape
。
例如:
new Regex(@"\b(" + string.Join("|", women.Select(Regex.Escape).ToArray()) + @"\b)");