Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用变量和字符串替换正则表达式中的模式_C#_Regex - Fatal编程技术网

C# 使用变量和字符串替换正则表达式中的模式

C# 使用变量和字符串替换正则表达式中的模式,c#,regex,C#,Regex,我在执行以下搜索和替换时遇到问题: // Consider this string - Note that it may be much more complicated, with many more matches string output = "\"$type\": \"SomeType\","; // The variable to search and replace - In this case is set to &q

我在执行以下搜索和替换时遇到问题:

// Consider this string - Note that it may be much more complicated, with many more matches
string output = "\"$type\": \"SomeType\",";

// The variable to search and replace - In this case is set to "SomeType"
string myType = "SomeType";

// The non-working regex
output = Regex.Replace(output, @"\"\$type\"\:\s\"" + myType + @"\",", "NewType");
我预计会有以下产出:

"$type": "NewType",
而不是:

"$type": "SomeType",
我认为这里有两个问题,但我无法理解语法。一个是使用字符串“type”,另一个是我没有使用捕获组,因此在输出字符串中只有myType被“NewType”替换。

您想使用


output=Regex.Replace(output,$@)(?哇,比我想象的要复杂得多,非常感谢!如果myType是在字符串的下面一行定义的,但必须像以前那样插入,那该怎么办?我可以这样做吗:Regex.Replace(g,$@)(?@stackMeUp您可以在Regex模式中使用任意数量的变量。谢谢,我找到了:-)