Reputation: 207
I'd like to get a group in the middle. For example:
startGOALend => GOAL
GOALend => GOAL
GOAL => GOAL
I'm trying (start)?(.*)(end)?
, but it doesn't lead to needed result.
var regex = new Regex("(start)?(.*)(end)?");
if (text == null) return;
var match = regex.Match(text);
foreach (var group in match.Groups)
{
Console.Out.WriteLine(group);
}
It returns:
startGOALend
start
GOALend
How could I solve it by regular expressions?
Upvotes: 0
Views: 34
Reputation: 6975
You want to avoid capturing the start
and end
groups. You can avoid capturing the contents of a pair of parentheses by putting ?:
at the start.
You also need to make the capture of the middle part lazy, so that it doesn't capture end
as part of the middle part. You can do this by putting a ?
after the *
.
So altogether, you get:
(?:start)?(.*?)(?:end)?$
Upvotes: 2