a?)(?a?)(?b?)(?b?)"); and line strin...">

Change regex group priority

I have the following regex:

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

and line

string str = @"ab";

When applying this regex to the string I get

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

Is it possible to change this regex to get

 g1 -> "a", g2 -> "", g3 -> "",  g4 -> "b"
? That is I want to have higher priority for g4 than for g3.
+3
source share
1 answer

You can achieve this with lazy "(compared to the default greedy) ?. Try the following:

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

Source: https://habr.com/ru/post/1728904/


All Articles