C # Regex matches words from a list

I have the following problem with my regex, I would like it to match the caterpillar in the line "This is a caterpillar 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); } 
+6
c # regex
source share
1 answer

You will need a regular expression of the form \b(abc|def)\b .
\b is a word delimiter.

In addition, you need to call Regex.Escape for each word.

For example:

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

All Articles