【问题标题】:Look for substring in string with item followed to searched sentence在字符串中查找子字符串,项目后跟搜索的句子
【发布时间】:2018-07-15 18:05:05
【问题描述】:

在 C# 中找到字符串中的子字符串并在搜索语句后跟单词检索它的正确方法是什么,例如在字符串中:

 string str = "On the screen the faint, old, robed figure of Mercer toiled upward, and all at once a rock sailed past him.";

搜索子字符串:

 string find = "figure of";

获得所需的输出:

 figure of Mercer

【问题讨论】:

  • 也看看 string.IndexOf,有时这就是你所需要的(还有 IndexOfAny 和 LastIndexOf...)
  • 当你有figure of --speech--- 时会发生什么?
  • @sln 你好,这只是获取搜索实例的跟随词的例子,也可以是不同的搜索词组
  • @Flydog57 你好,字符串 indexOf、indexOfAny 和 LastIndexOf,你能举出任何特定目标的例子吗
  • 我得到了它的工作,但它太复杂了。使用正则表达式;它要简单得多。处理空白是一件很痛苦的事情。

标签: c# regex


【解决方案1】:

你可以试试这个模式([inputString] +(\\w+))

使用正则表达式group 和空格来获取单词。

string search = "figure of";
string str = "On the screen the faint, old, robed figure of Mercer toiled upward, and all at once a rock sailed past him.";
string regex_Str = string.Format("({0} +([\\w+]+))", search);
var result = new Regex(regex_Str).Match(str);
Console.WriteLine(result.Value);

c# online

【讨论】:

  • 您好,({0} * ([a-zA-Z]+))({0} +([\\w+]+)) 有什么区别?
  • [a-zA-Z]+ 与 ` [\\w+]+, *` 相同,表示匹配 01,+ 表示匹配多于 1 个信息,您可以查看此链接rexegg.com/regex-quickstart.html
猜你喜欢
  • 1970-01-01
  • 2015-03-20
  • 2019-10-06
  • 2020-08-25
  • 2014-03-17
  • 1970-01-01
  • 2017-06-30
  • 1970-01-01
相关资源
最近更新 更多