gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:04:48 24 4
gpt4 key购买 nike

如何使用在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com