开发者

Modifying regex group priority

开发者 https://www.devze.com 2022-12-16 13:53 出处:网络
I have the following Regex: Regex regex = new Regex(@\"(?<g1>a?)(?<g2>a?)(?<g3>b?)(?<g4>b?)\");

I have the following Regex:

Regex regex = new Regex(@"(?<g1>a?)(?<g2>a?)(?<g3>b?)(?<g4>b?)");

and a string

string str = @"ab";

When applying this regex to the string I get

 g1 -> "a", g2 -> "", g3 -> "b",  g4 -> ""

Is it possible to modify this 开发者_运维知识库regex to get

 g1 -> "a", g2 -> "", g3 -> "",  g4 -> "b"
? That is I want to have higher priority for g4 than for g3.


You should be able to achieve this with a "lazy" (compared to the default "greedy") ?. Try this:

Regex regex = new Regex(@"(?<g1>a?)(?<g2>a?)(?<g3>b??)(?<g4>b?)");
0

精彩评论

暂无评论...
验证码 换一张
取 消