Preserving Word Integrity with String Replacement
In programming, the need often arises to replace specific words or phrases within a string. However, when dealing with text containing partial word matches, it's crucial to maintain the integrity of whole words. Here's how to achieve this using String.Replace with a twist.
To replace only whole words, a regular expression (regex) approach is the most effective. Regex provides the ability to match specific patterns within a string.
Let's consider the following example:
"test, and test but not testing. But yes to test".Replace("test", "text")
The desired output is:
"text, and text but not testing. But yes to text"
To accomplish this, create a regex pattern that matches the word "test" as a whole word. This can be achieved using word boundaries, represented by the b metacharacter. Here is the modified regex pattern:
\btest\b
The complete C# code using the regex 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 above is the detailed content of How Can I Replace Whole Words in a String While Preserving Partial Word Matches?. For more information, please follow other related articles on the PHP Chinese website!