简体   繁体   中英

Find and replace using regular expressions

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 achieve 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM