简体   繁体   English

使用C#中的Regex用'$ _'替换字符串的奇怪行为

[英]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: $$_ 要解决您的问题,您可能需要像这样转义: $$_

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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