【问题标题】:String search using <List> of substrings使用子字符串的 <List> 进行字符串搜索
【发布时间】:2015-12-12 16:42:05
【问题描述】:

问题与这些非常相似:

Check a string for containing a list of substrings

Check if a string contains a list of substrings and save the matching ones

有一个例外 - 不仅要检查而且要获取子字符串的起始索引以供将来处理。它可能看起来像 IndexOf 使用 List 的字符串:

private List<string> matches = new List<string> { "one", "two", "three" };

while (index < text.Length && -1 != (index = text.IndexOf(matches, index))) 
{                       
   ...
   // also I need to identify which one of substrings has been matched
   index += matches[?].Length;
   // further text processing...
}

换句话说,我需要知道文本字符串是否包含列表中的任何子字符串(不是单词!),如果包含,则获取匹配子字符串的开始和结束位置。

P.S:另外,这个方法必须足够快并且不区分大小写。

【问题讨论】:

  • 你输入的字符串是什么?
  • 您刚刚通过在标签中添加Regex 回答了您自己的问题...使用它! Match 类为您提供了很多能力.. 比如获得 IndexLength 之类的..
  • 我没有成功使用正则表达式。我能够匹配我的子字符串,但下一步是什么?如何获得职位? >> 喜欢获取索引或长度之类的东西.. 哦,我不知道。稍后会尝试...
  • >>你的输入字符串是什么? -- 取任何包含上面列出的子字符串的字符串。例如。 "twoBrownFoxJumpedThreetimesblabla oneblabla"

标签: c# regex string


【解决方案1】:

这是获取匹配关键字索引的 LINQ 方法:

var matches = new List<string> { "one", "two", "three" };
var result = matches.Where(i => s.IndexOf(i, StringComparison.OrdinalIgnoreCase) > -1)
           .ToDictionary(m => s.IndexOf(m, StringComparison.OrdinalIgnoreCase), m => m);

使用StringComparison.OrdinalIgnoreCase,我们确保不区分大小写的比较检查。

非LINQ方式:

List<string> matches = new List<string> { "one", "two", "three" };
for (int h = 0; h < matches.Count; h++)
{
    int idx = s.IndexOf(matches[h], StringComparison.OrdinalIgnoreCase);
    if (idx > -1)
        Console.WriteLine(string.Format("Index: {0}, value: {1}",idx, matches[h]));
 }

这是一种获取匹配字典及其在输入字符串中的索引的正则表达式方法:

List<string> matches = new List<string> { "one", "two", "three" };
matches = matches.Select(p => Regex.Escape(p)).ToList();
string s = "one and two and three";
var dict = Regex.Matches(s, string.Join("|", matches), RegexOptions.IgnoreCase).Cast<Match>()
                .ToDictionary(m => m.Index, m => m.Value);

结果:

您需要使用 Match.Index 来获取字符串中匹配项的索引,但要确保您的正则表达式模式有效,Regex.Escape 可能会有所帮助(因为您可能有 ? 或其他正则表达式特殊字符在搜索词中)。

RegexOptions.IgnoreCase 标志将确保不区分大小写的匹配。

【讨论】:

  • 会不会比使用基本字符串方法快N倍?
  • @UlugbekUmirov:不知道,但如果正则表达式被编译并用作静态只读字段,它会非常快。我猜您正在写自己的答案-请这样做。我只是想展示如何使用Regex 来完成它。
  • 谢谢,它完成了这项工作。有没有不使用正则表达式的快速解决方案?
  • 我添加了另一个基于 LINQ 的解决方案。请检查。但是有一个区别:Regex 返回匹配的实际关键字(在实际情况下),但 LINQ 返回找到的关键字。
  • 感谢 LINQ,但有针对 .NET 2.0 的解决方案吗? (但这并不重要)
猜你喜欢
  • 2014-03-06
  • 1970-01-01
  • 2013-08-09
  • 2020-09-27
  • 2013-04-23
  • 2016-06-21
  • 2013-11-09
  • 1970-01-01
  • 2019-10-06
相关资源
最近更新 更多