C#正则表达式匹配字符串中的多个单词

Nis*_*sho 6 c# regex

如何使用在C#中运行的正则表达式找到字符串中的所有匹配项?

我想在下面的示例字符串中找到所有匹配项.例:

inputString: Hello (mail) byebye (time) how are you (mail) how are you (time)
Run Code Online (Sandbox Code Playgroud)

我想匹配(mail),并(time)从示例.包括括号().

在试图解决这个问题时,我写了下面的代码.

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
}
Run Code Online (Sandbox Code Playgroud)

pipe(|)用于逻辑OR条件吗?

Fis*_*rdo 10

使用Regex.Escape(testString)是为了逃避你的管道角色,转身

@"(mail)|(time)" 
Run Code Online (Sandbox Code Playgroud)

有效地进入

@"\(mail\)\|\(time\)".
Run Code Online (Sandbox Code Playgroud)

因此,你的正则表达式正在寻找文字"(mail)|(time)".

如果你的所有匹配都像parens包围的单词一样简单,我会像这样建立正则表达式:

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);
Run Code Online (Sandbox Code Playgroud)