0

I have some string like this one:

DEV_NUM_26 - Some type...TYPE0 with support of some functions

My target is to get next data: (id=26, type=TYPE0)

Expression is looks like this:

    (?<id>(?<=DEV_NUM_) \d{0,3}) \s-\s (?<name>(?<=Some \s type \.+) \w+)

but I got 0 match results and the problem is in second (?<=). If I try to make something like:

    (?<id>(?<=DEV_NUM_) \d{0,3}) \s-\s (?<name>Some \s type \.+ \w+)

I got next result: (id=26, type=Some type...TYPE0).

The first and main question is how to fix this expression) And last but not least is why excluding prefix (?<=) doesn't work at the end of expression? As I understand, it suppose to find a part of expression in brackets and ignore it, like in the first part of expression, but it doesn't...

1
  • See hwnd's answer below for a working Regex. But for an explanation of why yours didn't work, it's because the second zero-width positive lookbehind ignored the fact that the preceding text was in fact present in the string being evaluated. So, (?<id>(?<=DEV_NUM_) \d{0,3}) \s-\s Some\stype\.+(?<name>(?<=Some \s type \.+) \w+) would work (but so verbose!), as would (?<id>(?<=DEV_NUM_) \d{0,3}) \s-\s [\w\d\s\.]+(?<name>(?<=Some \s type \.+) \w+) (less verbose, but still not as clean as hwnd's answer below). Commented Oct 23, 2014 at 21:56

1 Answer 1

1

Instead, place the parts you don't want to include outside of your named capturing groups. Note: I removed the Positive Lookbehind assertions from your expression because they are really not necessary here.

String s = "DEV_NUM_26 - Some type...TYPE0 with support of some functions";
Match m  = Regex.Match(s, @"DEV_NUM_(?<id>\d{0,3})\s-\sSome\stype\.+(?<name>\w+)");
if (m.Success)
    Console.WriteLine(m.Groups["id"].Value);   //=> "26"
    Console.WriteLine(m.Groups["name"].Value); //=> "TYPE0"

If you want to shorten your expression, you could write it as ...

@"(?x)DEV_NUM_ (?<id>\d+) [^.]+\.+ (?<name>\w+)"
Sign up to request clarification or add additional context in comments.

Comments

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.