![](/img/trans.png)
[英]RegEx.Replace to Replace Whole Words and Skip when Part of the Word
[英]How to Replace [Word] with Word using Regex.Replace and should replace whole word only
我正在做一個翻譯項目。 我遇到的一個問題是當我試圖替換單詞特殊字符時。
例如:
[Animal] can be furry.
Dog is an [Animal].
我需要用Animal
替換[Animal]
。 請注意,我只需要替換整個單詞。 所以結果如下:
Animal can be furry.
Dog is an Animal.
而且,正如我所說的,它應該是整個詞。 所以,如果我有:
[Animal][Animal][Animal] can be furry.
- 結果應該仍然是
[Animal][Animal][Animal] can be furry.
- 沒有什么事發生,因為[Animal]
與[Animal][Animal][Animal]
樣品:
string originalText1 = "[Animal] can be furry";
string badText ="[Animal]";
string goodText = "Animal";
Regex.Replace(originalText1, Regex.Escape(badText), Regex.Escape(goodText));
一切都好。 但正如我所說,我需要替換整個詞。 並與上面的代碼,“ [Animal]can be furry
”將被替換為“ Animalcan be furry
”,這是一個無無。
所以我也嘗試過:
Regex.Unescape(
Regex.Replace(
Regex.Escape(originalText1),
String.Format(@"\b{0}\b", Regex.Escape(badText)),
Regex.Escape(goodText)))
但仍然無法奏效。 而現在我迷路了。 請幫忙。
我還想提一下幾乎有類似的帖子,但這個問題並不需要僅替換整個單詞。 我在網上看了將近3個小時都無濟於事。 對你的幫助表示感謝。 謝謝!
我沒有測試過,但我會嘗試這個:
Regex.Replace(orginalText, @"\b\[Animal\]\b", "Animal");
這只會在字邊界匹配[Animal](\\ b)
這適合我。 嘗試一下,如果您正在尋找它,請告訴我。
string originalText1 = "[Animal] can be furry";
string badText = @"(?:(?<=^|\s)(?=\S)|(?<=\S|^)(?=\s))" + Regex.Escape("[Animal]") + @"(?:(?<=\S)(?=\s|$)|(?<=\s)(?=\S|$))";
string goodText = "Animal";
string newString = Regex.Replace(originalText1, badText, goodText);
Console.WriteLine(newString);
//"Animal can be furry"
originalText1 = "[Animal]can be furry";
newString = Regex.Replace(originalText1, badText, goodText);
Console.WriteLine(newString);
//"[Animal]can be furry"
在這里找到。
我認為這里最簡單的方法是使用后視和前瞻來確保括號內的文本是“真正的”匹配。 我不確定您的具體要求,但看起來您正在尋找:
[Animal]
) Dog is an [Animal].
一段時間Dog is an [Animal].
第一個很容易: \\[Animal\\]
。
對於第二個,您可以使用后視來確保前面的字符是合適的:
(?<=(^|\\s))
,最后一次預測: (?=($|\\s|\\.))
這意味着整個正則表達式將是:
var pattern = @"(?<=^|\s)\[Animal\](?=$|\s|\.)";
var output = Regex.Replace(input, pattern, "Animal");
您可能需要在適當的時候向前瞻/后方添加額外的標點符號。
對於您問題中的示例:
Input: "[Animal] can be furry."
Output: "Animal can be furry."
Input: "Dog is an [Animal]."
Output: "Dog is an Animal."
Input: "[Animal][Animal][Animal] can be furry."
Output: "[Animal][Animal][Animal] can be furry."
Input: "[Animal]can be furry"
Output: "[Animal]can be furry"
對我來說,這有效:
string s = @"[Animal][Animal][Animal] can be furry. - nothing happened as [Animal] is not the same as [Animal][Animal][Animal]
[Animal] can be furry.
[Animal]
can [Animal]
be furry
my [Animal] is furry";
string mask = "(^|\\s)\\[Animal\\](\\s|$)";
string rep = "$1Animal$2";
string s2 = "";
s2 = Regex.Replace(mask, rep);
/*
s2 = "[Animal][Animal][Animal] can be furry. - nothing happened as Animal is not the same as [Animal][Animal][Animal]
Animal can be furry.
Animal
can Animal
be furry
my Animal is furry" */
你還可以在面具中添加“特殊字符”:
string mask = "(^|\\s|'|\")\\[Animal\\](\\s|$|,|\\?|\\.|!|'|\")";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.