A regex to extract a string between two metrics WITHOUT also returning delimiters?
I just want to extract the text between the brackets - NOT the brackets either!
My code looks like this:
var source = "Harley, J. Jesse Dead Game (2009) [Guard]"
// Extract role with regex
m = Regex.Match(source, @"\[(.*)\]");
var role = m.Groups[0].Value;
// role is now "[Guard]"
role = role.Substring(1, role.Length-2);
// role is now "Guard"
Can you help me simplify this to just one regex, not regex and then a substring?
+2
a source to share
2 answers
a different group number is used. Every time you wrap something in () it creates a new group from it. Group zero is the complete expression found. group1 is the first group (), group2 is the second, etc. Since you are using group 0, it returns the entire string that matches the expression
Try changing groups [x] to 1 and see what it gives you.
+5
a source to share
You can use zero-width assertions ( ?=
) and lookbehind ( ?<=
):
m = Regex.Match(source, @"(?<=\[).*(?=\])");
var role = m.Value;
- Zero-width positive expectation assertion: matches the suffix but excludes it from the capture
- Zero-width lookbehind positive assertion: matches the prefix but excludes it from capturing
See Grouping Constructs on MSDN for more details .
0
a source to share