简体   繁体   English

Regex.Replace用匹配的字符串替换

[英]Regex.Replace with matched string in the replacement

I would like to compactly insert a <br /> tag before every line break in a string with regular expressions in C#. 我想在C#中使用正则表达式的字符串中的每个换行符之前紧凑地插入<br />标签。 Can this be done? 能做到吗? Currently, I am only able to replace the line break with the following: 目前,我只能将换行符替换为以下内容:

myString = Regex.Replace(myString, @"\r\n?|\n", "<br />");

Can I modify this to include the matched text (ie either \\r\\n , \\r , or \\n ) in the replacement? 我可以修改它以在替换中包含匹配的文本(即\\r\\n\\r\\n )吗?

Clearly, it can be done with a separate Match variable, but I'm curious if it can be done in one line. 显然,可以使用单独的Match变量完成此操作,但是我很好奇是否可以在一行中完成。

使用括号捕获换行符,并使用$1使用替换中捕获的内容:

myString = Regex.Replace(myString, @"(\r\n?|\n)", "<br />$1");

MSDN has a separate page just for .NET's regex substitution magic . MSDN有一个单独的页面,仅用于.NET的正则表达式替换魔术

While the others are correct that the most general approach is to capture something and write back the captured contents with $n (where n is the captured group number), in your case you can simply write back the entire match with $& : 尽管其他方法是正确的,但最通用的方法是捕获某些内容并用$n写回捕获的内容(其中n是捕获的组号),在您的情况下,您可以简单地用$&写回整个匹配项:

myString = Regex.Replace(myString, @"\r\n?|\n", "<br />$&");

If you are doing this a lot then avoiding the capturing could be a bit more efficient. 如果您经常这样做,那么避免捕获可能会更有效率。

你可以用做替代在“替换”字符串:

Regex.Replace(myString, @"(\r\n?|\n)", "$1<br />");

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

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