开发者

Find and replace using regular expressions

开发者 https://www.devze.com 2023-01-24 10:18 出处:网络
I need to search for following search strings and replace it with a new value. string searchString1 = \"#TEST1#\";

I need to search for following search strings and replace it with a new value.

string searchString1 = "#TEST1#";
string searchString2 = "#TEST1#AT#";

How do I achie开发者_开发知识库ve this using C#/regular expressions?


Check out the Regex object, specifically Regex.Replace. Bonus example.

And some code...

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


I'm not sure why you need to use regular expressions for this.

What is it about

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

that doesn't do what you want?


Match the regular expression, get the start index and the length of the match, remove the old and splice in the new. Repeat.

You might also do all your matching at once, storing the starts and lengths, then applying the splicing backwards (so as not to affect your indexes)

0

精彩评论

暂无评论...
验证码 换一张
取 消