简体   繁体   中英

Regular expression (.NET): how to get a group in the middle

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?

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)?$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM