Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

c# - Get the shortest substrings between two multicharacter delimiters

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...