Get the shortest substrings between two multicharacter delimiters

后端 未结 1 1592
我寻月下人不归
我寻月下人不归 2020-12-22 09:45

I have

string text = \"aa aa value kk 8718764 aa value1 kk kk kk 5178gkjh aathtkhkk\";

I want to get all texts between aa and

相关标签:
1条回答
  • 2020-12-22 10:36

    The .*? will still match aa in between aa and kk.

    Use a tempered greedy token:

    aa((?:(?!aa).)*?)kk
       ^^^^^^^^^^^^^
    

    or

    aa((?:(?!aa|kk).)*)kk
       ^^^^^^^^^^^^^^^
    

    See the regex demo

    Details:

    • aa - an aa substring
    • ((?:(?!aa).)*?) - Group 1 capturing any zero or more chars (if RegexOptions.Singleline option used, even including newline) that are not starting an aa substring sequence, as few as possible
    • kk - a kk substring

    C# code:

    var re = @"aa((?:(?!aa).)*?)kk";
    var str = "aa aa value kk 8718764 aa value1 kk kk kk 5178gkjh aathtkhkk"; 
    var res = Regex.Matches(str, re)
        .Cast<Match>()
        .Select(p => p.Groups[1].Value)
        .ToList();
    
    0 讨论(0)
提交回复
热议问题