Jesse Sierks
Jesse Sierks

Reputation: 2397

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?

Upvotes: 2

Views: 2682

Answers (3)

Alan Moore
Alan Moore

Reputation: 75222

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.

Upvotes: 5

Hari Prasad
Hari Prasad

Reputation: 16956

You could use Linq LastOrDefault or Last to get the last match from MatchCollection.

var lastMatch = Regex.Matches(input,"hello") 
                     .OfType<Match>()
                     .LastOrDefault();

Check this Demo

Or, as @jdweng mentioned in the comment, you could even access using index.

Match lastMatch = matches[matches.Count - 1];

Upvotes: 0

Lanister
Lanister

Reputation: 155

Regex regex = new Regex("REGEX"); 
var v = regex.Match("YOUR TEXT");
string s = v.Groups[v.Count - 1].ToString();

Upvotes: 0

Related Questions