C# Regex.Replace删除'\r';“中的字符”\r\n“;

C# Regex.Replace删除'\r';“中的字符”\r\n“;,c#,.net,regex,C#,.net,Regex,下面是一个简单的例子 string text = "parameter=120\r\n"; int newValue = 250; text = Regex.Replace(text, @"(?<=parameter\s*=).*", newValue.ToString()); string text=“parameter=120\r\n”; int newValue=250; text=Regex.Replace(text,@”(?默认情况下与\n不匹配。如果要匹配,必须使用单行模式

下面是一个简单的例子

string text = "parameter=120\r\n";
int newValue = 250;

text = Regex.Replace(text, @"(?<=parameter\s*=).*", newValue.ToString());
string text=“parameter=120\r\n”;
int newValue=250;

text=Regex.Replace(text,@”(?
默认情况下与
\n
不匹配。如果要匹配,必须使用单行模式

(?s)(?<=parameter\s*=).*
 ^
(?s)(?看一看。简而言之,句点(
)匹配几乎所有正则表达式实现中除
\n
以外的所有字符。与替换无关,特别是-您告诉它删除任何数量的
,这也会使
\r
变得混乱

现在无法测试,但您可以将其重写为
(?尝试以下操作:

string text = "parameter=120\r\n";
int newValue = 250;

text = Regex.Replace(text, @"(parameter\s*=).*\r\n", "${1}" + newValue.ToString() + "\n");
文本的最终值

参数=250\n


显式匹配回车符和换行符。将只匹配以
\r\n

结尾的行。您的示例在.Net(看起来像php或perl)上不起作用,但带有
\r\n
的正则表达式工作正常
text=regex.Replace(text,@”(?@Max你试过了吗?在.net 4.0和.net 4.5下对我很有用。我假设震动语法是${1}-它将模式匹配的反向引用插入替换字符串。是的,我试过了。结果是
“$1250\n”
。是的,${1}让我困惑:)@Max我做了一次编辑,将“$1”改为“${1}”因为这是您引用的结果。“${1}”对我来说非常有效。您使用的是.net的哪个版本?