[英]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)?
我正在尝试
(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. 您要避免捕获
start
和end
组。 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. 您还需要使对中间部分的捕获变得懒惰,以使它不会捕获作为中间部分一部分的
end
。 You can do this by putting a ?
您可以通过放置一个
?
after the *
. 在
*
。
So altogether, you get: 因此,您总共得到:
(?:start)?(.*?)(?:end)?$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.