Replacing Whole Words with String.Replace
In string processing, it often becomes necessary to replace specific words within a text. However, using String.Replace may result in undesired partial matches. This article explores a technique to ensure that only whole words are replaced.
Using Regular Expressions
To replace only whole words, regular expressions provide a convenient solution. The b metacharacter is used to match word boundaries, which helps identify the complete presence of the word.
C# Example
In C#, the following code demonstrates this 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);
VB.NET Example
For VB.NET, the equivalent code is:
Dim input As String = "test, and test but not testing. But yes to test" Dim pattern As String = "\btest\b" Dim replace As String = "text" Dim result As String = Regex.Replace(input, pattern, replace) Console.WriteLine(result)
Key Points
The above is the detailed content of How Can I Replace Whole Words in a String Without Affecting Partial Matches?. For more information, please follow other related articles on the PHP Chinese website!