C#Regex匹配列表中的单词

时间:2010-12-26 19:11:22

标签: c# regex

我的正则表达式存在以下问题,我希望它能匹配字符串中的 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);
        }

1 个答案:

答案 0 :(得分:13)

您需要\b(abc|def)\b形式的正则表达式 \b是一个单词分隔符。

此外,您需要在每个单词上调用Regex.Escape

例如:

new Regex(@"\b(" + string.Join("|", women.Select(Regex.Escape).ToArray()) + @"\b)");