Luke Makk
Luke Makk

Reputation: 1197

find and replace with regex C#

    string subject = "/testfolder
    subject = Regex.Replace(subject, "|d|", "17");
    Console.Write(subject);

getting output as 17/17o17u17t17g17o17i17n17g17

why is the above find and replace failing, it should do nothing but instead it's filling in the replace variable at every single space. Does it even require regular expression?

Upvotes: 0

Views: 125

Answers (1)

xanatos
xanatos

Reputation: 111940

You know that in |d| the | means or? Try escaping it! @"\|d\|"

Your regular expression was equivalent to "" (empty string).

This because you must see it as

(match of empty string) or (match of letter d) or (match of empty string)

always matched from left to right, stop at the first positive match. As we will see, just the first condition (match of empty string) is positive everywhere, so it won't ever go to the other matches.

Now, the regex parser will try to match your regex at the start of the string.

It is at "/" (first character): does it match? is "" part of "/"? Yes (at least in the "mind" of the regex parser). Now the funny thing is that Regex.Replace will replace the matched part of the string with 17... But funnily the matched part of "/" is "", so it will replace an imaginary empty string that is just before the "/" with "17". So it will become "17/"

Now it will go to the next character (because normally the regex will be tried starting at the end of the previous match, but with a caveat written below), the t, redo the same and replace it with "17t", so we will have at this point:

17/17t

and so on.

There is a last little trick (taken from msdn)

When a match attempt is repeated by calling the Matches method, the regular expression engine gives empty matches special treatment. Usually, the regular expression engine begins the search for the next match exactly where the previous match left off. However, after an empty match, the regular expression engine advances by one character before trying the next match.

Upvotes: 10

Related Questions