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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With