C#正则表达式匹配来自列表的单词

9

我有一个正则表达式的问题,我希望它能匹配字符串"This is a caterpillar s tooth"中的caterpillar,但它却匹配了cat。我该如何修改它?

        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个回答

15
你需要一个形如\b(abc|def)\b的正则表达式。
\b代表单词分隔符。
此外,你需要对每个单词调用Regex.Escape
例如:
new Regex(@"\b(" + string.Join("|", women.Select(Regex.Escape).ToArray()) + @"\b)");

谢谢,但我为什么需要 Regex.Escape 呢?只用 \b 不就可以了吗? - Grant Smith
如果你的字符串中包含\字符,该怎么办? - SLaks
应该是\b(abc|def)\b还是\b(abc|def\b) - 您的C#示例给出了与第一行示例不同的结果。 - Gerwald

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接