0

I was using StringBuilder.Replace() to change some "keywords" to my own methods, but since it doesn't match the whole word I need to find a way to replace it correctly.

string example = "Hey $name! Welcome to $namewebsite!";
StringBuilder sb = new StringBuilder(example);
sb.Replace("$name", "getName()");
sb.Replace("$namewebsite", "getWebSiteName()");
return sb;

Above the output will be "Hey getName()!, Welcome to getName()website!", so I'm trying to use RegEx to match the whole word.

string example = "Hey $name! Welcome to $namewebsite!";
example = Regex.Replace(example, "\b$name\b", "getName()");
example = Regex.Replace(example, "\b$namewebsite\b", "getWebSiteName()");
return example;

But since the "keyword" has the symbol "$" it doesn't work, at least that's what I think, because it doesn't replace any of the "keywords".

Of course it's just a small example of my code, I have like 30+ keywords starting with "$" to replace to methods names.

3
  • Did you try escaping it with \$? Commented Feb 23, 2015 at 17:02
  • Put a backslash in front of the $ to escape it, i.e. use "\$". Or alternatively Regex.Escape("$name") Commented Feb 23, 2015 at 17:02
  • When I use te Regex.Escape("$name") it keep replacing the $namewebsite to getName()website Commented Feb 23, 2015 at 17:53

2 Answers 2

1

The issue here doesn't need to be solver with RegEx. It's the order in which you are doing the replacements. This is because the first search is a substring of the second. Switch them round and it will work.

string example = "Hey $name! Welcome to $namewebsite!";
StringBuilder sb = new StringBuilder(example);
sb.Replace("$namewebsite", "getWebSiteName()");
sb.Replace("$name", "getName()");
return sb;

Working example: https://ideone.com/kHwHUT

Another way to solve this would be to put a delimiter at the END of the search string as well as the start. For example:

string example = "Hey $name$! Welcome to $namewebsite$!";
StringBuilder sb = new StringBuilder(example);
sb.Replace("$name$", "getName()");
sb.Replace("$namewebsite$", "getWebSiteName()");
return sb;
Sign up to request clarification or add additional context in comments.

Comments

0

The symbol $ is a special character in regular expressions which denotes the end of a string. You need to escape it if you want to use it as a literal:

Try using \$ instead of $.

For more information: http://regexlib.com/CheatSheet.aspx?AspxAutoDetectCookieSupport=1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.