我的正则表达式有以下问题,我希望它匹配字符串 "This is a caterpillar s tooth" 中的 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);
}
最佳答案
您需要一个 \b(abc|def)\b
形式的正则表达式。
\b
是单词分隔符。
此外,您需要对每个单词调用 Regex.Escape
。
例如:
new Regex(@"\b(" + string.Join("|", women.Select(Regex.Escape).ToArray()) + @"\b)");
关于C# 正则表达式匹配列表中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4535055/