在字符串中查找子字符串以在搜索句子之前找到部分

时间:2018-07-20 01:57:27

标签: c# regex string linq substring

在:

 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";

如果这样的话:

 string reg = string.Format("({0} +([\\w+]+))", find);
 var result = new Regex(reg).Match(str);

我可以跟踪搜索到的句子

figure of Mercer

但是如何在搜索的句子之前找到短语的一部分:

 On the screen the faint, old, robed

仅获取最近的单词:

 robed

1 个答案:

答案 0 :(得分:1)

IndexOf将有助于找到Substing的起始索引

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";

var index = str.IndexOf(find);

if (index >= 0)
{
    var result = str.Substring(0, index);
    Console.WriteLine(result);
}