【问题标题】:Look for substring in string to find part before searched sentence在字符串中查找子字符串以在搜索的句子之前找到部分
【发布时间】:2018-07-20 01:57:26
【问题描述】:

在:

 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

【问题讨论】:

    标签: c# regex string linq substring


    【解决方案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);
    }
    

    【讨论】:

    • 您好,是的,您如何只得到第一个单词?我已经编辑了问题
    • 如果你有你要找的索引,string.Substring(可能与一个或两个 string.Length 结合)会让你找到你正在看的任何一块 - 相对于什么你最初找到的。
    猜你喜欢
    • 2020-08-25
    • 1970-01-01
    • 2011-04-14
    • 2015-03-20
    • 2016-12-08
    • 2012-02-10
    • 1970-01-01
    • 2016-03-23
    • 2011-07-13
    相关资源
    最近更新 更多