C# 删除字符串的内容,包括特定单词及其后的内容

C# 删除字符串的内容,包括特定单词及其后的内容,c#,substring,C#,Substring,我需要获取一个字符串,然后删除它的内容,包括指定短语和之后的内容,然后返回剩下的最后一个单词。 在本例中,“更多信息” 基本上,这个脚本应该使用字符串 "Please visit this website for more information if you have questions" 并返回“ (请注意,这只是一个示例,字符串可以是任何东西,我故意用换行符将其弄乱,因为有一半时间它看起来就是这样的。) 下面的split方法有效,返回最后一个单词,但substring方

我需要获取一个字符串,然后删除它的内容,包括指定短语和之后的内容,然后返回剩下的最后一个单词。 在本例中,“更多信息”

基本上,这个脚本应该使用字符串

     "Please visit 

this 
website
 for more information if you have questions"
并返回“

(请注意,这只是一个示例,字符串可以是任何东西,我故意用换行符将其弄乱,因为有一半时间它看起来就是这样的。)

下面的split方法有效,返回最后一个单词,但substring方法无效

知道我做错了什么吗

   public static string InfoParse(string input)


{
    string extract = input;


    extract =  input.Substring(0, input.IndexOf("more information"));


    extract = extract.Split(' ').Last();

    return extract;



}
更改为:

    public static string InfoParse(string input)
    {
        //string extract = input;
        string extract = input.Substring(0, input.IndexOf("more information"));
        extract = extract.Split(new string[] {" ", "\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries).Last();
        return extract;
    }
或者通过以下步骤显示代码的错误:

public static string InfoParse(string input)
{
    //string extract = input;
    string extract = input.Substring(0, input.IndexOf(" more information"));
    extract = extract.Split(' ').Last();
    return extract;
}
拆分返回的条目位于最后一个空格之后,最后一个空格正好是“更多信息”-->之前的空格,因此它返回一个空字符串


编辑:现在也可以使用linebreak

使用RegularExpression:

using System.Text.RegularExpressions;

string InfoParse(string input, string word)
{
    Match m = Regex.Match(input, @"\s?(?<LastBefore>\w+)\s+" + word, RegexOptions.Singleline);
    if (m.Success)
        return m.Groups["LastBefore"].Value;
    return null;
}
使用System.Text.regular表达式;
字符串InfoParse(字符串输入、字符串字)
{
Match m=Regex.Match(输入@“\s”(?\w+\s+”+字,RegexOptions.Singleline);
如果(m.成功)
返回m.Groups[“LastBefore”]值;
返回null;
}

第一个问题显然更可靠(考虑到他们的“换行符等弄乱了”),最好也不要指望使用一致的空格。没错,只是想说明原始问题源的确切问题它是有效的,但它将换行符视为最后一句话的一部分。有没有办法让它将换行符当作空格来解析最后一个单词?我已经编辑了我的答案,只使用第一种方法,现在换行符也可以了