如何使用在 C# 中运行的正则表达式查找字符串中的所有匹配项?
我想在下面的示例字符串中找到所有匹配项。 示例:
inputString: Hello (mail) byebye (time) how are you (mail) how are you (time)
我想匹配示例中的 (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
}
管道(|
) 是否用于逻辑OR
条件?
最佳答案
使用 Regex.Escape(testString)
将转义您的管道字符,转义
@"(mail)|(time)"
有效进入
@"\(mail\)\|\(time\)".
因此,您的正则表达式正在寻找文字 "(mail)|(time)"
。
如果您的所有匹配都像被括号包围的单词一样简单,我会像这样构建正则表达式:
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);
关于C# 正则表达式匹配字符串中的多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23014574/