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:
- Why the string "$_" causes this behavior?
- How to workaround this?