I need a way to have this:
"test, and test but not testing. But yes to test".Replace("test", "text")
return this:
"text, and text but not testing. But yes to text"
Basically I want to replace whole words, but not partial matches.
NOTE: I am going to have to use VB for this (SSRS 2008 code), but C# is my normal language, so responses in either are fine.
You could use the string.replace
I just want to add a note about this particular regex pattern (used both in the accepted answer and in ReplaceWholeWord function). It doesn't work if what you are trying to replace isn't a word.
Here a test case:
(ready to try code: http://ideone.com/2Nt0A)
This has to be taken into consideration especially if you are doing batch translations (like I did for some i18n work).
A regex is the easiest approach:
The important part of the pattern is the
\b
metacharacter, which matches on word boundaries. If you need it to be case-insensitive useRegexOptions.IgnoreCase
:As commented by Sga, the regex solution isn't perfect. And I guess not performance friendly too.
Here is my contribution :
... With test cases :
If you want to define what characters make up a word i.e. "_" and "@"
you could use my (vb.net) function:
Test
Result
I've created a function (see blog post here) that wraps regex expression, suggested by Ahmad Mageed