0
    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?

1 Answer 1

10

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.

4
  • I mean the string will literally have |d| in it, not or
    – Luke Makk
    Commented Aug 16, 2013 at 14:40
  • 3
    He is saying you need to escape the | character so the code interprets it right.
    – sealz
    Commented Aug 16, 2013 at 14:41
  • 1
    @LukeMakk I know. Use what I wrote.
    – xanatos
    Commented Aug 16, 2013 at 14:41
  • @LukeMakk If you want I can even explain what your regex did :-)
    – xanatos
    Commented Aug 16, 2013 at 14:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.