Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex.Replace with groups duplicated output? [duplicate]

Tags:

c#

regex

I have a weird problem with Regex.Replace.

I think my immediate window says it all:

pattern
"([^_]*)(.*)"

fileNameToReplicate
"{Productnr}_LEI1.JPG"

Regex.Replace(fileNameToReplicate, pattern, $"$1")
"{Productnr}"

Regex.Replace(fileNameToReplicate, pattern, $"$2")
"_LEI1.JPG"

Regex.Replace(fileNameToReplicate, pattern, $"sometext$2")
"sometext_LEI1.JPGsometext"

Thus, my pattern looks for the first underscore and captures everything until that underscore in group1.

Then it captures the rest of the text (starting with that underscore until the end of the string) and captures that as group 2.

The regex captures correctly, look here to review it.

Why is the prefixed text outputted twice? Once before the group, and once after the group. Obviously I expected to have this is output:

"sometext_LEI1.JPG"

like image 656
bas Avatar asked Apr 24 '26 22:04

bas


1 Answers

It does not matter how many X-stars occur in sequence:

(.*)(.*)(.*)(...

since there is a position called end of subject string that all of them will match it. To see your expected result change your pattern to:

^([^_]*)(.*)

Above adds a caret which defines a boundary and makes engine to not start a match right at the end of input string.

like image 77
revo Avatar answered Apr 26 '26 12:04

revo