Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

c# - 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A regex is the easiest approach:

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

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

Regex.Replace(input, pattern, replace, RegexOptions.IgnoreCase);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...