Home >Backend Development >C++ >How Can I Replace Whole Words in a String While Preserving Partial Word Matches?

How Can I Replace Whole Words in a String While Preserving Partial Word Matches?

Susan Sarandon
Susan SarandonOriginal
2025-01-04 21:15:40460browse

How Can I Replace Whole Words in a String While Preserving Partial Word Matches?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn