gpt4 book ai didi

c# - 每个关键字都需要存在

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:04 25 4
gpt4 key购买 nike

比如有几个句子:

xx received by 2 sent from 1
yy received by 3 sent from 1
zz received by 1 sent from 3
aa received by 4 sent from 1

如何找到所有包含1 3的句子?

我需要的结果是

yy received by 3 sent from 1
zz received by 1 sent from 3

在这种情况下。

我尝试过的最接近的是 Regex r = new Regex (".*(3).*(1).*"); 但显然这不是解决方案。

最佳答案

您可以使用 LINQ 代替正则表达式:

var strs = new string[] { "xx received by 2 sent from 1",
"yy received by 3 sent from 1",
"zz received by 1 sent from 3",
"aa received by 4 sent from 1" };
var myres = strs.Where(p => p.Contains("1") && p.Contains("3")).ToList();

enter image description here

如果您更喜欢正则表达式方法(它会更慢):

 ^(?=.*1)(?=.*3).*

参见 demo (如果要使用 IsMatch(),则不需要在模式末尾使用 .*)。

var rx = new Regex(@"^(?=.*1)(?=.*3)");
var myres2 = strs.Where(p => rx.IsMatch(p)).ToList();

正则表达式匹配

  • ^ - 字符串的开头然后...
  • (?=.*1) - 确保从字符串的开头至少有一个 1
  • (?=.*3) - 确保从字符串的开头至少有一个 3(再次!) .

(?=...) 构造被称为正向预测,即所谓的look-arounds 之一。 :

Lookaround actually matches characters, but then gives up the match, returning only the result: match or no match.

因此,当您连续进行 2 次前瞻时,它们都在输入字符串中的相同位置“运行”,并且我们采用逻辑 AND 方式。在 Lookarounds Stand their Ground 中查看更多相关信息.

关于c# - 每个关键字都需要存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31470927/

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