Varad
Varad

Reputation: 17

Using Regex.Replace() instead of string.Replace()

I have a Dictionary<string , string> dict and a string script. I want to replace each occurrence of key in script with corresponding value from the Dictionary in such a way that only tokens which are same as key are replaced.

Example

Dictionary dict has the following entries :

"name" : "John"
"age"  : "34"

and

string script = " The name and the fathersname and age and age_of_father "

Output after Replace should be :

script = " The John and the fathersname and 34 and the age_of_father " 

I have tried using string.Replace() but it doesn't work. How can I accomplish this using Regex.Replace() and concept of Lookahead ?

Upvotes: 0

Views: 150

Answers (2)

Flydog57
Flydog57

Reputation: 7111

What does "doesn't work" mean in your question? What are you seeing? What does your code look like?

Remember that strings are immutable, and string.Replace doesn't change the original string, it returns a new string with the changes made.

For things like this (looping while doing a lot of replacements), StringBuilder.Replace is often a better choice. StringBuilder instances are mutable, so StringBuilder.Replace does its work in-place.

Do the following:

  • Initialize a StringBuilder with your script string
  • Loop through you dictionary doing replacements
  • When finished, call ToString on the StringBuilder to get the result

I wish there was a way to get StringBuilder and Regex to work together.

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Let's match each word (\w+ the simplest pattern: word is a sequence of one or more unicode word characters) and check (with a help of the dictionary) if it should be replaced:

Dictionary<string, string> dict = 
  new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
    { "name", "John"},
    { "age", "34"}
  };

string script = " The name and the fathersname and age and age_of_father ";

//  The John and the fathersname and 34 and age_of_father 
string result = Regex.Replace(
  script,
 @"\w+",   // match each word
  match => dict.TryGetValue(match.Value, out var value) // should the word be replaced? 
    ? value          // yes, replace
    : match.Value);  // no, keep as it is

Upvotes: 1

Related Questions