Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying regex group priority

Tags:

c#

regex

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.
like image 339
StuffHappens Avatar asked Sep 01 '26 08:09

StuffHappens


1 Answers

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?)");
like image 69
Lucero Avatar answered Sep 03 '26 01:09

Lucero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!