簡體   English   中英

僅替換整個單詞C#

[英]Replace only whole words c#

我正在嘗試創建一個僅替換整個單詞的函數,例如:

句子:“#testing是#test”,如果我使用Replace(“#test”,“ #cool”),我將擁有“ #cooling if #cool”,但我想擁有“ #testing is#涼”

我進行了搜索,發現的每個答案都是:

string pattern = @"\b"+previousText+"\b";
string myText = Regex.Replace(input, pattern, newText, RegexOptions.IgnoreCase);

但是,如果我的previousText(我要替換的文本)包含“#”,則此解決方案不起作用。

我的previousText和newText都可以以“#”開頭。

解決方案是什么?

編輯:多虧了圖例,如果單詞后面有空格,則正則表達式現在可以使用,但是如果搜索到的單詞在逗號旁邊,則不能使用正則表達式:

string input = "#test, #test";
            string patternTest = @"#test";
            string newTextTest = "#cool";
            string result = Regex.Replace(input, @"(?:(?<=^|\s)(?=\S|$)|(?<=^|\S)(?=\s|$))" + patternTest + @"(?:(?<=^|\s)(?=\S|$)|(?<=^|\S)(?=\s|$))", newTextTest, RegexOptions.IgnoreCase);

這將返回:“ #test,#cool”而不是“ #cool,#cool”

以下正則表達式將僅替換單個單詞

var input = "#testing is #test";
var pattern = @"#test";
string myText = 
Regex.Replace(input, @"(?:(?<=^|\s)(?=\S|$)|(?<=^|\S)(?=\s|$))" + pattern + @"(?:(?<=^|\s)(?=\S|$)|(?<=^|\S)(?=\s|$))","#cool", RegexOptions.IgnoreCase);


結果:

#測試很酷


這應該在單詞前后直接使用逗號和分號

var input = "#test, is ;#test";
var searchString = @"#test";
var replaceWith = "#cool";
var pattern = @"(?:(?<=^|(\s|,|;))(?=\S|$)|(?<=^|\S)(?=\s|$))" 
              + searchString + 
              @"(?:(?<=^|(\s))(?=\S|$)|(?<=^|\S)(?=(\s|,|;)|$))";

string myText = Regex.Replace(input, pattern, replaceWith, RegexOptions.IgnoreCase);

結果:

#cool,是; #cool


這個字詞將與字詞前后的所有以下字符一起使用

例如:

  1. ,單詞或單詞,
  2. 字; 或;單詞
  3. .word或....

,; -'

 var input = "#test's is #test."; var searchString = @"#test"; var replaceWith = "#cool"; var pattern = @"(?:(?<=^|(\\s|,|;|-|:|\\.|'))(?=\\S|$)|(?<=^|\\S)(?=\\s|$))" + searchString + @"(?:(?<=^|(\\s))(?=\\S|$)|(?<=^|\\S)(?=(\\s|,|;|-|:|\\.|')|$))"; string myText = Regex.Replace(input,pattern ,replaceWith, RegexOptions.IgnoreCase); 

結果:

#cool's是#cool。

如果由於某種原因不想使用正則表達式,也可以不使用正則表達式:

var split_options = new [] {' ', '.', ',' ...}; // Use whatever you might have here.
var input =  "#testing is #test".Split( split_options
                                      , StringSplitOptions.RemoveEmptyEntries);
var word_to_replace = "#test";
var new_text = "#cool";
for (int i = 0; i < input.Length; i++)
{
    if (input[i].Equals(word_to_replace))
    input[i] = new_text;
}
var output = string.Join(" ",input);

// your output is "#testing is #cool"

您可以將其放在方法或擴展方法中,這也使您的代碼更干凈。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM