Search code examples
vb.netstring.net-2.0replace

VB.NET match whole word and replace


I'm trying to replace a string with another but the problem is that the string is matching some other string partially.

For e.g. -

Dim x as String = "I am Soham"
x = x.Replace("am","xx")

After this replace I would only like the word am to replaced with xx but because my name also contains am its also getting replaced.

The value of x is I xx Sohxx. How can I stop this. Please help.


Solution

  • Use Regex.Replace and use the regular expression \bam\b. In a regular expression \b means "word boundary".