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
Release: 2025-01-04 21:15:40
Original
454 people have browsed it

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")
Copy after login

The desired output is:

"text, and text but not testing.  But yes to text"
Copy after login

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
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template