且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取两个多字符定界符之间的最短子字符串

更新时间:2022-11-14 16:47:24

.*?仍将在 aa kk .

使用

C#代码:

  var re = @"aa((?:( ?! aa).)*?)kk";var str ="aa aa值kk 8718764 aa值1 kk kk kk 5178gkjh aathtkhkk";var res = Regex.Matches(str,re).Cast< Match>().Select(p => p.Groups [1] .Value).ToList(); 

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 kk and the expected results are:

1 = value
2 = value1
3 = thtkh

I try using a "aa(.*?)kk" regex, but I am not getting the expected result.

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();