Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex match multiple words in a string

Tags:

c#

regex

How can I find all the matches in a string using a regular expression run in C#?

I want to find all matches in the below example string. Example:

inputString: Hello (mail) byebye (time) how are you (mail) how are you (time)

I want to match (mail) and (time) from the example. Including parentheses( and ).

In attempting to solve this, I've writtent the following code.

string testString = @"(mail)|(time)";  

Regex regx = new Regex(Regex.Escape(testString), RegexOptions.IgnoreCase);
List<string> mactches = regx.Matches(inputString).OfType<Match>().Select(m => m.Value).Distinct().ToList();

foreach (string match in mactches)
{
    //Do something
}

Is the pipe(|) used for the logical OR condition?

like image 969
Nisho Avatar asked Apr 11 '14 13:04

Nisho


1 Answers

Using Regex.Escape(testString) is going to escape your pipe character, turning

@"(mail)|(time)" 

effectively into

@"\(mail\)\|\(time\)".

Thus, your regex is looking for the literal "(mail)|(time)".

If all of your matches are as simple as words surrounded by parens, I would build the regex like this:

List<string> words   = new List<string> { "(mail)", "(time)", ... };
string       pattern = string.Join("|", words.Select(w => Regex.Escape(w)));
Regex        regex   = new Regex(pattern, RegexOptions.IgnoreCase);
like image 83
FishBasketGordo Avatar answered Sep 18 '22 13:09

FishBasketGordo