gpt4 book ai didi

c# - 使用正则表达式以任意顺序查找两个字符串

转载 作者:太空宇宙 更新时间:2023-11-03 21:51:27 26 4
gpt4 key购买 nike

例如我有一个输入:"Test your Internet connection bandwidth. Test your Internet connection bandwidth."(重复两次)我想搜索字符串internet带宽

string keyword = tbSearch.Text //That holds value: "internet bandwidth"
string input = "Test your Internet connection bandwidth. Test your Internet connection bandwidth.";

Regex r = new Regex(keyword.Replace(' ', '|'), RegexOptions.IgnoreCase);
if (r.Matches(input).Count == siteKeyword.Split(' ').Length)
{
//Do something
}

这不起作用,因为它找到了 2 个“internet”和 2 个“bandwidth”,所以它计数为 4,但关键字长度为 2。那我能做什么?

最佳答案

var pattern = keyword.Split()
.Aggregate(new StringBuilder(),
(sb, s) => sb.AppendFormat(@"(?=.*\b{0}\b)", Regex.Escape(s)),
sb => sb.ToString());

if (Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase))
{
// contains all keywords
}

第一部分是根据您的关键字生成模式。如果有两个关键字 "internet bandwidth",那么生成的正则表达式模式将如下所示:

"(?=.*\binternet\b)(?=.*\bbandwidth\b)"

它将匹配以下输入:

"Test your Internet connection bandwidth."
"Test your Internet connection bandwidth. Test your Internet bandwidth."

以下输入将不匹配(并非包含所有单词):

"Test your Internet2 connection bandwidth bandwidth."
"Test your connection bandwidth."

另一个选项(分别验证每个关键字):

var allWordsContained = keyword.Split().All(word => 
Regex.IsMatch(input, String.Format(@"\b{0}\b", Regex.Escape(word)), RegexOptions.IgnoreCase));

关于c# - 使用正则表达式以任意顺序查找两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14339693/

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