我需要搜索以下搜索字符串并将其替换为新值。
string searchString1 = "#TEST1#";
string searchString2 = "#TEST1#AT#";
如何使用C#/正则表达式实现此目的?
答案 0 :(得分:3)
查看Regex对象,特别是Regex.Replace。奖金example。
还有一些代码......
// Assuming 'input' is the original string, and that 'replacementstring1'
// and 'replacementstring2' contain the new info you want to replace
// the matching portions.
input = Regex.Replace(input, "#TEST1#AT#", replacementstring2); // This search pattern wholly
// contains the next one, so
// do this one first.
input = Regex.Replace(input, "#TEST1#", replacementstring1);
答案 1 :(得分:0)
我不确定为什么你需要使用正则表达式。
它是什么
string replaced = inString.Replace(searchString1,"replacement1")
.Replace(searchString2,"replacement2");
这不符合你的要求?
答案 2 :(得分:0)
匹配正则表达式,获取起始索引和匹配的长度,删除旧的和旧的拼接。重复。
您也可以一次完成所有匹配,存储开始和长度,然后向后应用拼接(以免影响索引)