Get string between two strings in a string

前端 未结 23 2208
别跟我提以往
别跟我提以往 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:28

    If you want to handle multiple occurrences of substring pairs, it won't be easy without RegEx:

    Regex.Matches(input ?? String.Empty, "(?=key : )(.*)(?<= - )", RegexOptions.Singleline);
    
    • input ?? String.Empty avoids argument null exception
    • ?= keeps 1st substring and ?<= keeps 2nd substring
    • RegexOptions.Singleline allows newline between substring pair

    If order & occurrence count of substrings doesn't matter, this quick & dirty one may be an option:

    var parts = input?.Split(new string[] { "key : ", " - " }, StringSplitOptions.None);
    string result = parts?.Length >= 3 ? result[1] : input;
    

    At least it avoids most exceptions, by returning the original string if none/single substring match.

提交回复
热议问题