Jesse Sierks Jesse Sierks - 3 months ago 6
C# Question

Find the Last Match in a Regular Expression

I have a string and a regular expression that I am running against it. But instead of the first match, I am interested in the last match of the Regular Expression.

Is there a quick/easy way to do this?

I am currently using Regex.Matches, which returns a MatchCollection, but it doesn't accept any parameters that will help me, so I have to go through the collection and grab the last one. But it seems there should be an easier way to do this. Is there?

Answer

The .NET regex flavor allows you to search for matches from right to left instead of left to right. It's the only flavor I know of that offers such a feature. It's cleaner and more efficient than the traditional methods, such prefixing the regex with .*, or searching out all matches so you can take the last one.

To use it, pass this option when you call Match() (or other regex method):

RegexOptions.RightToLeft 

More information can be found here.