如何在c#中替换第二次出现的字符串? [英] How to replace second occurrence of string in c# ?
本文介绍了如何在c#中替换第二次出现的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用Regex.Replace()方法用特定模式替换主字符串中第二次出现的Sub字符串。
Ex。
I want to replace second occurrence of Sub string in my main string with particular pattern using Regex.Replace() Method.
Ex.
<table>
<tr>
<td></td>
</tr>
</table>
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
我的字符串上面有两个表格标签。我想替换第二次出现的表标记
I have above string with two table tags. I want replace second occurrence of table tag
<table>
<table id="mytable1">
。
如何只用我的模式替换第二次出现的表格。 ?
.
How can i replace only second occurrence of table with my pattern. ?
推荐答案
你可以使用它
You can use it
public string Replace2ndOccurence(string inputStr, string valueToReplace2ndOccurance)
{
Match m = Regex.Match(inputStr, "((" + Regex.Escape(valueToReplace2ndOccurance) + ").*?){2}");
int index = 0;
if (m.Success)
index = m.Groups[2].Captures[1].Index;
return inputStr.Remove(index, valueToReplace2ndOccurance.Length);
}
也许你可以使用XML而不是正则表达式:
Maybe you can use XML instead of Regex:
var doc = XDocument.Parse(@"<root><table>
<tr>
<td></td>
</tr>
</table>
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table></root>");
var secondTable = doc.Root.Elements("table").Skip(1).First();
secondTable.SetAttributeValue("id", "mytable1");
var replaced = doc.ToString();
使用这个替换字符串的解决方案
Use this solution to replace the string
public string Replace2ndOccurence(string inputStr, string valueToReplace2ndOccurance,string newString)
{
Match m = Regex.Match(inputStr, "((" + Regex.Escape(valueToReplace2ndOccurance) + ").*?){2}");
int index = 0;
if (m.Success)
index = m.Groups[2].Captures[1].Index;
inputStr = inputStr.Remove(index, valueToReplace2ndOccurance.Length);
return inputStr.Insert(index, newString);
}
这篇关于如何在c#中替换第二次出现的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文