开发者

C# Regex to match words from list

开发者 https://www.devze.com 2023-02-01 01:09 出处:网络
I have a following problem with my regular expression, I wo开发者_如何学Culd like it to match caterpillar in the string \"This is a caterpillar s tooth\" but it matches cat. How can I change it?

I have a following problem with my regular expression, I wo开发者_如何学Culd like it to match caterpillar in the string "This is a caterpillar s tooth" but it matches cat. How can I change it?

        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);
        }


You need a regex of the form \b(abc|def)\b.
\b is a word separator.

Also, you need to call Regex.Escape on each word.

For example:

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

精彩评论

暂无评论...
验证码 换一张
取 消