[英]How to replace some part of the text using regex c#
for example: 例如:
string str = $@"<html> < head > </ head > < body > <start> < h1 > Header 1 </ h1 > < p > A worker can be of 3 different types.</ p > <end> < p ></ p > </ body > </ html > "
string replacement = "hello world";
string newString = $@"<html> < head > </ head > < body > <start> < h1 > Header 1 </ h1 > < p > hello world</ p > <end> < p ></ p > </ body > </ html > "
So I have a <start>
and <end>
sign to know which part of the text should be replaced. 因此,我有一个
<start>
和<end>
标记来知道应替换文本的哪一部分。 How I can get the newString
by regex. 我如何通过正则表达式获取
newString
。
Using Regex.Replace
you set the pattern from the first <r>
to the second, including all that is in between. 使用
Regex.Replace
您可以将模式设置为从第一个<r>
到第二个<r>
,包括介于两者之间的所有内容。 Then you specify what to replace with. 然后,指定要替换的内容。
var result = Regex.Replace(str, "<start>.*?<end>", $"<start> {replacement} <end>");
If prior to C# 6.0 string interpolation then: 如果在C#6.0字符串插值之前,则:
var result = Regex.Replace(str, "<start>.*?<end>", string.Format("<start> {0} <end>",replacement));
With latest string from comments: 使用注释中的最新字符串:
string str = $@"<html> < head > </ head > < body > <start> < h1 > Header 1 </ h1 > < p > A worker can be of 3 different types.</ p > <end> < p ></ p > </ body > </ html > ";
string replacement = "hello world";
var result = Regex.Replace(str, "<start>.*?<end>", $"<start> {replacement} <end>");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.