【问题标题】:Find equal substring in list of strings在字符串列表中查找相等的子字符串
【发布时间】:2019-06-22 03:56:27
【问题描述】:

我正在研究如何在大字符串列表中找到相等的子字符串。

这个方法很好用:

var results = myList.FindAll(delegate (string s) { return s.Contains(myString); });

但它也会查找带有部分单词的子字符串,例如,如果我正在寻找“you do”,它还会发现额外的“you dont”,因为包含“you do..”

如果是字符串,这种方法似乎可以得到想要的结果:

 bool b = str.Contains(myString);
 if (b)
 {
     int index = str.IndexOf(myString);    
 }

如何获得与列表相同类型的匹配

【问题讨论】:

  • 最简单的方法可能是使用正则表达式(例如\byou do\b
  • @John 你好,我不确定使用正则表达式在大字符串列表中查找子字符串,它必须是我猜的每个字符串
  • 列表有多大?
  • @John 大约 50 000 个字符串

标签: c# regex linq substring contains


【解决方案1】:

您可以使用正则表达式返回一组潜在术语的所有匹配项:

string[] stringsToTest = new [] { "you do", "what" };
var escapedStrings = stringsToTest.Select(s => Regex.Escape(s)); // escape the test strings so that we can safely build them into the expression
var regex = new Regex("\\b(" + string.Join("|", escapedStrings) + ")\\b");
var matches = regex.Matches("How you do? How you don't? What you do? How you do what you do?");

如果您只有一个术语,您可以将其重写为:

var regex = new Regex(string.Format("\\b({0})\\b", Regex.Escape("you do")));
var matches = regex.Matches("How you do? How you don't? What you do? How you do what you do?");

然后您可以匹配使用match.Groups[0](对于匹配集合中的每个组)来获取匹配值:

foreach (Match m in matches)
{
    Console.WriteLine(string.Format("Matched {0} at {1}", m.Groups[0].Value, m.Groups[0].Index));
}

Try it online

【讨论】:

  • 所以,如果我的列表List<string> myList = new List<string>(); 包含大约 50 000 个字符串,例如“你怎么做?你怎么不做?你做什么?你怎么做?”,那么在这种情况下每个字符串都必须在循环中使用var matches = regex.Matches(myString) 处理,对吧?
  • 你确定,这不是本案的硬处理吗?
  • 您将使用IndexOf(不是您当前使用的Contains)获得更好的性能,然后检查匹配字符串之后的下一个字符。这取决于您真正需要它的效率。测试一下。如果太慢,请优化。
  • 你的意思是IndexOfdelegate
  • 我的意思是你在下提供的代码“如果是字符串,这个方法似乎给出了想要的结果:”
猜你喜欢
  • 2012-05-16
  • 2023-04-03
  • 2018-09-27
  • 2015-03-12
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
  • 2011-04-10
相关资源
最近更新 更多