Regex to match multiple strings


I need to create a regex that can match multiple strings. For example, I want to find all the instances of "good" or "great". I found some examples, but what I came up with doesn't seem to work:


Can anyone point me in the right direction?

Edit: I should note that I don't want to just match whole words. For example, I may want to match "ood" or "reat" as well (parts of the words).

Edit 2: Here is some sample text: "This is a really great story." I might want to match "this" or "really", or I might want to match "eall" or "reat".

3/30/2009 7:13:27 PM

Accepted Answer

If you can guarantee that there are no reserved regex characters in your word list (or if you escape them), you could just use this code to make a big word list into @"(a|big|word|list)". There's nothing wrong with the | operator as you're using it, as long as those () surround it. It sounds like the \w* and the \b patterns are what are interfering with your matches.

String[] pattern_list = whatever;
String regex = String.Format("({0})", String.Join("|", pattern_list));
3/26/2013 1:30:01 AM


after your edit:


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow