Easy but hard Regex
I have some data like that in a file.
Start
Status:good<>
Status:bad<>
Status:dfsf<>开发者_Python百科;
Status:gosdfsfod<>
Status:dogEatsCat<>
Some randomdata
End
<> is just end of status information I just want to get last status. This one "dogEatsCat".
This regex is returning me all the statuses.
Status:(.+?)<>
But I just want to get the last one.
Then use a greedy capture before your regex:
.*Status:(.+?)<>
(You may need to swith to single-line mode such that .
matches also newlines.)
Alternatively you can use right-to-left mode for your regex match.
A working example for both options can be found here.
You could use the regex that you have, but only pay attention to the last match.
EDIT
Alternatively, you can grab all matches and return the last match captured. This can be done like the following:
Regex lastRegex = new Regex(@".*Status:(.+?)<>");
MatchCollection allMatches = lastRegex.Matches(sample);
if (allMatches.Count > 0)
{
Console.WriteLine(allMatches[allMatches.Count-1].Groups[1].Value);
}
精彩评论