2

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
6
  • 1
    Please post some code that shows what you're doing. The problem might not be with the regex but with how you're extracting the result. Commented Jun 3, 2019 at 10:17
  • Can you use .* to consume the initial part? Commented Jun 3, 2019 at 10:19
  • (?<=-)([0-9]+)(?=_)? If we can guarantee that exepected result is a number; (?<=-)([^\-]+?)(?=_) Commented Jun 3, 2019 at 10:21
  • The point is that . matches any char. If you know there must be no other - in between - and _ use [^-] instead of the dot. Commented Jun 3, 2019 at 10:25
  • 1
    The accepted answer is not accurate considering "I need the last occurrence". It will return all occurrences. Commented Jun 3, 2019 at 23:32

2 Answers 2

4

Let's try a bit different pattern:

(?<=-)([^-_]+?)(?=_)

we use [^-_] instead of .: all characters except - and _

Sign up to request clarification or add additional context in comments.

1 Comment

- at the initial position in the character class does not have to be escaped. Actually, you do not need a non-greedy quantifier, use greedy one.
2

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];

1 Comment

Efficient and takes into account, that OP wants to match the last occurence which eg this regex doesn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.