0

I am copying a delimited substring from a string to another. The delimiters are #! and !#. The first string have my "Immutable Content" and I want to put it inside another string.

For example:

Original String:

"Lorem Ipsum #! My Immutable Content !# Lorem Ipsum"

Template String:

"This is a test #!-!# It worked."

Produces:

"This is a test #! My Immutable Content !# It worked."

This works fine. But if my original string has the string '$_' the result string is unexpected:

Original String:

"Lorem Ipsum #! My Immutable $_ Content !# Lorem Ipsum"

Produces:

"This is a test #! My Immutable This is a test #!-!# It worked. Content !# It worked."

It seems the original string is all inside the new string.

The code that produces this result is listed below

string content = "Lorem Ipsum #! My Immutable $_ Content !# Lorem Ipsum";
string template = "This is a test #!-!# It worked.";

Regex regexOld = new Regex(@"(?<all>#!(?<text>[\w\d\s.""\r\n':;\{\}\[\]\(\)\+\-\*!@#$%^&<>,\?~`_|\\\/=]*)!#)");
MatchCollection mcOld = regexOld.Matches(content);

foreach (Match match in mcOld)
{
    Regex regexNew = new Regex(@"(?<all>#!(?<text>[\w\d\s.""\r\n':;\{\}\[\]\(\)\+\-\*!@#$%^&<>,\?~`_|\\\/=]*)!#)");
    template = regexNew.Replace(template, match.Groups["all"].Value);
}

I would like to know two things:

  1. Why the string "$_" causes this behavior?
  2. How to workaround this?
0

1 Answer 1

2

$_ has a special meaning in a replacement string, it represents the input string. To solve your problem, you probably need to escape it like this: $$_

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, that's fixed my problem. But, where I found some documentation about this?
Is it a general solution to replace all $ by $$? Or do we need to replace only the defined $number, ${name}, $& etc.? Is there a method provided by .NET which does Regex escaping? It seems that there's at least no RegexOption which would avoid such special meanings.
@ThomasW.: Yes, in other words, when you want a literal $ in the replacement pattern you must escape it with an other $.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.