Reputation: 2397
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
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
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
Reputation: 155
Regex regex = new Regex("REGEX");
var v = regex.Match("YOUR TEXT");
string s = v.Groups[v.Count - 1].ToString();
Upvotes: 0