简体   繁体   中英

How regex get last element's time between a sentence

eg
I'd like to get below sentence last agree time like pic.

input:

Agree|AAA Agree 7/28 22:34,Agree|BBBB Agree 7/28 23:20,Agree|CCC Agree 7/29 07:41,Agree|JJJ Agree 7/29 07:45,Agree|DDD Agree 7/29 07:54,forward|EEE forward 7/29 07:54,forward|FFF forward 7/29 07:54,forward|GGG forward 7/29 07:54,forward|HHHH forward 7/29 07:54

expected output:

7/29 07:54

image-20200729082045279

I've tried to use LINQ but i can only do it like the picture.

void Main()
{
    var input = "Agree|AAA Agree 7/28 22:34,Agree|BBBB Agree 7/28 23:20,Agree|CCC Agree 7/29 07:41,Agree|JJJ Agree 7/29 07:45,Agree|DDD Agree 7/29 07:54,forward|EEE forward 7/29 07:54,forward|FFF forward 7/29 07:54,forward|GGG forward 7/29 07:54,forward|HHHH forward 7/29 07:54";
    var output = input.Split('|')
        .Where(_ => _.Contains("Agree")).Select((e, index) => new {e,index})
        .OrderByDescending(_=>_.index)
        .Take(1);
}

图像-20200729082008606

This regex would do the trick

Agree (\d{1,2}\/\d{1,2} \d{1,2}:\d{1,2})(?!.*Agree \d{1,2}\/\d{1,2} \d{1,2}:\d{1,2})

This means Agree \d{1,2}\/\d{1,2} \d{1,2}:\d{1,2} not followed by any occurence of Agree \d{1,2}\/\d{1,2} \d{1,2}:\d{1,2}

Then you would do this to extract 7/29 07:54 into lastAgree variable

string pattern = @"Agree (\d{1,2}\/\d{1,2} \d{1,2}:\d{1,2})(?!.*Agree \d{1,2}\/\d{1,2} \d{1,2}:\d{1,2})";           

// Get your match using pattern
var match = Regex.Match(text, pattern);

// Groups[1] is (\d{1,2}\/\d{1,2} \d{1,2}:\d{1,2})
var lastAgree = match.Groups[1].Value; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM