[英]Replace whole word with a symbol using C# Regex
所以我正在嘗試使用正則表達式模式替換諸如@theplace
或@theplaces
類的詞:
String Pattern = string.Format(@"\b{0}\b", PlaceName);
但是當我進行替換時,找不到模式,我猜這是問題所在的@
符號。
有人可以告訴我我需要對Regex模式做些什么才能使其正常工作嗎?
以下代碼將用<replacement>
@thepalace
或@thepalaces
所有實例。
var result = Regex.Replace(
"some text with @thepalace or @thepalaces in it."
+ "\r\nHowever, @thepalacefoo and bar@thepalace won't be replaced.", // input
@"\B@thepalaces?\b", // pattern
"<replacement>"); // replacement text
?
使前面的字符s
可選。 我正在使用靜態Regex.Replace方法。 \\b
匹配單詞和非單詞字符之間的邊界。 \\B
匹配\\b
不匹配的每個邊界。 請參閱正則表達式邊界 。
結果
some text with <replacement> or <replacement> in it.
However, @thepalacefoo and bar@thepalace won't be replaced.
您的問題*是@
之前的\\b
(單詞邊界)。 空格和@
之間沒有單詞邊界。
您可以刪除它,或將其替換為無邊界(即大寫字母B
。
string Pattern = string.Format(@"\B{0}\b", PlaceName);
*假設PlaceName
以@
開頭。
嘗試這個:
string PlaceName="theplace", Replacement ="...";
string Pattern = String.Format(@"@\b{0}\b", PlaceName);
string Result = Regex.Replace(input, Pattern, Replacement);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.