Extract part of a string between point A and B

后端 未结 5 1045
遥遥无期
遥遥无期 2020-12-16 12:02

I am trying to extract something from an email. The general format of the email will always be:

blablablablabllabla hello my friend.

[what I want]

Goodbye          


        
相关标签:
5条回答
  • 2020-12-16 12:24

    You can simply calculate the length from the start and end

    const string startText = "hello my friend";
    var start = str.LastIndexOf(startText) + startText.Length;
    var end = str.IndexOf("Goodbye my friend");
    var length = end -start;
    str.Substring(start,length);
    
    0 讨论(0)
  • 2020-12-16 12:24

    try myStr.substring(start,end);

    0 讨论(0)
  • 2020-12-16 12:29

    you can also use Regex

    string s =  Regex.Match(yourinput,
                            @"hello my friend(.+)Goodbye my friend", 
                            RegexOptions.Singleline)
                .Groups[1].Value;
    
    0 讨论(0)
  • 2020-12-16 12:32

    Substring takes the start index (zero-based) and the number of characters you want to copy.

    You'll need to do some math, like this:

    string email = "Bla bla hello my friend THIS IS THE STUFF I WANTGoodbye my friend";
    int startPos = email.LastIndexOf("hello my friend") + "hello my friend".Length + 1;
    int length = email.IndexOf("Goodbye my friend") - startPos;
    string sub = email.Substring(startPos, length);
    

    You probably want to put the string constants in a const string.

    0 讨论(0)
  • 2020-12-16 12:35
    string s1 = "find a string between within a lengthy string";
    string s2 = s1.IndexOf("between").ToString();
    string output = s1.Substring(0, int.Parse(s2));
    Console.WriteLine("string before between is : {0}", output);
    Console.ReadKey();
    
    0 讨论(0)
提交回复
热议问题