有String.Replace的方法只打了"整个单词"

Vac*_*ano 69 .net c# vb.net string

我需要一种方法来做到这一点:

"test, and test but not testing.  But yes to test".Replace("test", "text")
Run Code Online (Sandbox Code Playgroud)

归还这个:

"text, and text but not testing.  But yes to text"
Run Code Online (Sandbox Code Playgroud)

基本上我想替换整个单词,但不是部分匹配.

注意:我将不得不使用VB(SSRS 2008代码),但C#是我的正常语言,因此两者中的响应都很好.

Ahm*_*eed 113

正则表达式是最简单的方法:

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);
Run Code Online (Sandbox Code Playgroud)

模式的重要部分是\b元字符,它与字边界相匹配.如果您需要它不区分大小写,请使用RegexOptions.IgnoreCase:

Regex.Replace(input, pattern, replace, RegexOptions.IgnoreCase);
Run Code Online (Sandbox Code Playgroud)

  • `\ b`是正则表达式,用于说明单词边界. (13认同)
  • 你的解决方案很棒!如果我发布了一个带有正则表达式转义的fn包装器:`static string ReplaceFullWords(string input,string from,string to){if(input == null){return null; } return Regex.Replace(input,"\\ b"+ Regex.Escape(from)+"\\ b",to); }` (4认同)
  • 该行应该是`string pattern = "\\btest\\b";` (2认同)

MiF*_*vil 21

我已经创建了一个函数(请参阅此处的博客文章),它包含正则表达式,由Ahmad Mageed建议

/// <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;
}
Run Code Online (Sandbox Code Playgroud)

  • 记得在`wordToFind`上使用`Regex.Escape()`,因此特殊字符被解释为常规字符. (4认同)

Ale*_*rot 7

正如Sga评论的那样,正则表达式解决方案并不完美.我猜也不会表现友好.

这是我的贡献:

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 ();
    }
}
Run Code Online (Sandbox Code Playgroud)

...对于测试用例:

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" ) );
Run Code Online (Sandbox Code Playgroud)

  • 我一直在使用它,发现一个失败:a = "4.99"; Console.WriteLine(a.ReplaceWholeWord("9", "8.99")); 结果为 4.98.99。在这种情况下,这看起来像一个愚蠢的例子,但它说明了我在实际项目中遇到的问题。 (2认同)

Sga*_*Sga 6

我只想添加一个关于这个特定正则表达式模式的注释(在接受的答案和ReplaceWholeWord函数中都使用)。如果您要替换的不是word ,则不起作用。

这里有一个测试用例:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

必须考虑到这一点,尤其是在您进行批量翻译时(就像我在一些 i18n 工作中所做的那样)。