Cornwell Cornwell - 1 year ago 94
C# Question

Regex capture order

I have this pattern:


And the replacement pattern is this:


The problem is that this word:


will be transformed to:


instead of


because for reason,
always takes precedence to
in the pattern.

How can I enforce the pattern to follow that order?

Answer Source

Use a lazy quantifier:


See the regex demo

The \w+ contains a greedy quantifier that: 1) grabs as many chars as it can (and note it can match s, i, all letters, digits and underscores) and then backtracks (yielding one char after another moving from right to left), trying to accommodate for the subsequent patterns. Since the in is found first, it is matched, and the whole group is considered matched, the regex goes on to check the end of string with $. A lazy quantifier will have the regex engine skip the \w+? after matching 1 word char, and other patterns will be tried, moving from left to right.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download