Get string between two strings in a string

前端 未结 23 2181
别跟我提以往
别跟我提以往 2020-11-22 09:46

I have a string like:

\"super exemple of string key : text I want to keep - end of my string\"

I want to just keep the string which is betw

相关标签:
23条回答
  • 2020-11-22 10:38

    I used the code snippet from Vijay Singh Rana which basically does the job. But it causes problems if the firstString does already contain the lastString. What I wanted was extracting a access_token from a JSON Response (no JSON Parser loaded). My firstString was \"access_token\": \" and my lastString was \". I ended up with a little modification

    string Between(string str, string firstString, string lastString)
    {    
        int pos1 = str.IndexOf(firstString) + firstString.Length;
        int pos2 = str.Substring(pos1).IndexOf(lastString);
        return str.Substring(pos1, pos2);
    }
    
    0 讨论(0)
  • 2020-11-22 10:39

    Something like this perhaps

    private static string Between(string text, string from, string to)
    {
        return text[(text.IndexOf(from)+from.Length)..text.IndexOf(to, text.IndexOf(from))];
    }
    
    0 讨论(0)
  • 2020-11-22 10:40

    Here is the way how i can do that

       public string Between(string STR , string FirstString, string LastString)
        {       
            string FinalString;     
            int Pos1 = STR.IndexOf(FirstString) + FirstString.Length;
            int Pos2 = STR.IndexOf(LastString);
            FinalString = STR.Substring(Pos1, Pos2 - Pos1);
            return FinalString;
        }
    
    0 讨论(0)
  • 2020-11-22 10:41

    In C# 8.0 and above, you can use the range operator .. as in

    var s = "header-THE_TARGET_STRING.7z";
    var from = s.IndexOf("-") + "-".Length;
    var to = s.IndexOf(".7z");
    var versionString = s[from..to];  // THE_TARGET_STRING
    

    See documentation for details.

    0 讨论(0)
  • 2020-11-22 10:43

    You can do it without regex

     input.Split(new string[] {"key :"},StringSplitOptions.None)[1]
          .Split('-')[0]
          .Trim();
    
    0 讨论(0)
  • 2020-11-22 10:47

    Perhaps, a good way is just to cut out a substring:

    String St = "super exemple of string key : text I want to keep - end of my string";
    
    int pFrom = St.IndexOf("key : ") + "key : ".Length;
    int pTo = St.LastIndexOf(" - ");
    
    String result = St.Substring(pFrom, pTo - pFrom);
    
    0 讨论(0)
提交回复
热议问题