Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to have String.Replace only hit "whole words"

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.

like image 637
Vaccano Avatar asked May 26 '11 18:05

Vaccano


People also ask

How do I replace a whole string in C#?

In C#, Replace() method is a string method. This method is used to replace all the specified Unicode characters or specified string from the current string object and returns a new modified string. This method can be overloaded by passing arguments to it.

How do you replace a word in a string with another word?

First travers the string and add spaces before and after punctuations. Split it into a list by splitting on just white spaces. Replacement process. Put the string back together.

How do you find and replace a word in a string in C#?

string res = str. Replace("Demo ", "New "); The following is the complete code to replace a word in a string.

How does regex replace work?

The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string. standardizes spacing in character data by replacing one or more spaces between text characters with a single space.


1 Answers

A regex is the easiest approach:

string input = "test, and test but not testing.  But yes to test"; string pattern = @"\btest\b"; string replace = "text"; string result = Regex.Replace(input, pattern, replace); Console.WriteLine(result); 

The important part of the pattern is the \b metacharacter, which matches on word boundaries. If you need it to be case-insensitive use RegexOptions.IgnoreCase:

Regex.Replace(input, pattern, replace, RegexOptions.IgnoreCase); 
like image 54
Ahmad Mageed Avatar answered Oct 12 '22 03:10

Ahmad Mageed