C# 使用正则表达式查找和替换

C# 使用正则表达式查找和替换,c#,regex,C#,Regex,我需要搜索以下搜索字符串并将其替换为新值 string searchString1 = "#TEST1#"; string searchString2 = "#TEST1#AT#"; 如何使用C#/正则表达式来实现这一点?请特别检查对象。奖金 还有一些代码 // Assuming 'input' is the original string, and that 'replacementstring1' // and 'replacementstring2' contain the new in

我需要搜索以下搜索字符串并将其替换为新值

string searchString1 = "#TEST1#";
string searchString2 = "#TEST1#AT#";
如何使用C#/正则表达式来实现这一点?

请特别检查对象。奖金

还有一些代码

// 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);
具体来说,请查看对象。奖金

还有一些代码

// 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);

我不知道你为什么要用正则表达式来做这个

是关于什么的

string replaced = inString.Replace(searchString1,"replacement1")
                          .Replace(searchString2,"replacement2");

这不符合您的要求吗?

我不知道您为什么需要使用正则表达式来实现这一点

是关于什么的

string replaced = inString.Replace(searchString1,"replacement1")
                          .Replace(searchString2,"replacement2");

这不符合您的要求?

匹配正则表达式,获取匹配的开始索引和长度,删除旧的并在新的中拼接。重复一遍


您还可以一次完成所有匹配,存储起始和长度,然后向后应用拼接(以免影响索引)

匹配正则表达式,获取起始索引和匹配长度,删除旧的和新的拼接。重复一遍


您也可以一次完成所有匹配,存储开始和长度,然后向后应用拼接(以免影响索引)

我假设这些只是示例,他需要在正则表达式类型模式上进行匹配。我假设这些只是示例,他需要匹配正则表达式类型的模式。感谢代码示例,但此方法的问题是第一行代码替换了“TEST1”的所有实例,包括“#TEST1#AT”,因为它还包含“#TEST1”令牌。我想要一个EXEXT模式匹配替换…这可能吗?重点是-只需颠倒两条语句的顺序。感谢代码示例,但此方法的问题是第一行代码替换了“TEST1”的所有实例,包括“TEST1”AT,因为它还包含“TEST1”我想要一个EXEXT模式匹配替换…这是可能的吗?注意-只需颠倒两个语句的顺序。