Reputation: 20625
I'm trying to extract string between two characters. First charachter has multiple occurences and I need the last occurence of first character. I've already checked similar questions but all suggested regexes don't work in case of multiple occurences of first character.
Example:
TEST-[1111]-20190603-25_TEST17083
My code:
string input = "TEST-[1111]-20190603-25_TEST17083";
var matches = Regex.Matches(input,@"(?<=-)(.+?)(?=_)");
var match = matches.OfType<Match>().FirstOrDefault();
var value = match.Groups[0].Value;
The current result:
[1111]-20190603-25
Expected result:
25
Upvotes: 2
Views: 373
Reputation: 16806
One option to get your result (and there are many options of course) is the following pattern:
.*-([0-9]*)_
and then get the first matched group (group with Id 1).
So your code will look like this:
var input = "[1111]-20190603-25";
var pattern = @".*-([0-9]*)_";
var match = Regex.Match(input, pattern);
var value = match.Groups[1];
Upvotes: 2
Reputation: 186668
Let's try a bit different pattern:
(?<=-)([^-_]+?)(?=_)
we use [^-_]
instead of .
: all characters except -
and _
Upvotes: 4