方式有String.Replace只打“整个单词”

我需要一个方法来拥有这个:

"test, and test but not testing. But yes to test".Replace("test", "text") 

返回这个:

 "text, and text but not testing. But yes to text" 

基本上我想replace整个单词,但不是部分匹配。

注:我将不得不使用VB(SSRS 2008代码),但C#是我的正常语言,所以在任何答复都很好。

正则expression式是最简单的方法:

 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); 

模式的重要组成部分是\b元字符,它与单词边界匹配。 如果你需要使用RegexOptions.IgnoreCase

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

我已经创build了一个函数(见这里的博客文章 ),包装正则expression式, 艾哈迈德马吉德build议

 /// <summary> /// Uses regex '\b' as suggested in https://stackoverflow.com/questions/6143642/way-to-have-string-replace-only-hit-whole-words /// </summary> /// <param name="original"></param> /// <param name="wordToFind"></param> /// <param name="replacement"></param> /// <param name="regexOptions"></param> /// <returns></returns> static public string ReplaceWholeWord(this string original, string wordToFind, string replacement, RegexOptions regexOptions = RegexOptions.None) { string pattern = String.Format(@"\b{0}\b", wordToFind); string ret=Regex.Replace(original, pattern, replacement, regexOptions); return ret; } 

正如Sga所评论的,正则expression式的解决scheme并不完美。 我猜也不是performance友好。

这是我的贡献:

 public static class StringExtendsionsMethods { public static String ReplaceWholeWord ( this String s, String word, String bywhat ) { char firstLetter = word[0]; StringBuilder sb = new StringBuilder(); bool previousWasLetterOrDigit = false; int i = 0; while ( i < s.Length - word.Length + 1 ) { bool wordFound = false; char c = s[i]; if ( c == firstLetter ) if ( ! previousWasLetterOrDigit ) if ( s.Substring ( i, word.Length ).Equals ( word ) ) { wordFound = true; bool wholeWordFound = true; if ( s.Length > i + word.Length ) { if ( Char.IsLetterOrDigit ( s[i+word.Length] ) ) wholeWordFound = false; } if ( wholeWordFound ) sb.Append ( bywhat ); else sb.Append ( word ); i += word.Length; } if ( ! wordFound ) { previousWasLetterOrDigit = Char.IsLetterOrDigit ( c ); sb.Append ( c ); i++; } } if ( s.Length - i > 0 ) sb.Append ( s.Substring ( i ) ); return sb.ToString (); } } 

…testing用例:

 String a = "alpha is alpha"; Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "alphonse" ) ); Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "alf" ) ); a = "alphaisomega"; Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "xxx" ) ); a = "aalpha is alphaa"; Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "xxx" ) ); a = "alpha1/alpha2/alpha3"; Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "xxx" ) ); a = "alpha/alpha/alpha"; Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "alphonse" ) ); 

我只是想添加关于这个特定的正则expression式模式的注释(在接受的答案和ReplaceWholeWord函数中都使用)。 如果你想要replace的不是一个字,它就不起作用。

这里是一个testing用例:

 using System; using System.Text.RegularExpressions; public class Test { public static void Main() { string input = "doin' some replacement"; string pattern = @"\bdoin'\b"; string replace = "doing"; string result = Regex.Replace(input, pattern, replace); Console.WriteLine(result); } } 

(准备尝试代码: http : //ideone.com/2Nt0A )

这是必须考虑的,特别是如果你正在做批量翻译(就像我为一些国际工作做的那样)。

C#代码(控制台应用程序)

上课程序

 { static void Main(string[] args) { Console.Write("Please input your comment: "); string str = Console.ReadLine(); string[] str2 = str.Split(' '); replaceStringWithString(str2); Console.ReadLine(); } public static void replaceStringWithString(string[] word) { string[] strArry1 = new string[] { "good", "bad", "hate" }; string[] strArry2 = new string[] { "g**d", "b*d", "h**e" }; for (int j = 0; j < strArry1.Count(); j++) { for (int i = 0; i < word.Count(); i++) { if (word[i] == strArry1[j]) { word[i] = strArry2[j]; } Console.Write(word[i] + " "); } } } }