简体   繁体   中英

Strange behavior to replace string with '$_' using Regex in C#

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?

$_ 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: $$_

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM