[英]Regex replace only matched strings - C#
我正在嘗試找出如何使用Regex.Replace方法來滿足我的需要,基本上我需要找到一個特定的單詞,該單詞的兩邊都沒有任何“ az”字母,而僅將匹配項替換為另一個單詞。
在下面的示例中,我搜索所有“ man ”出現並替換為“ coach ”。 我使用這種正則表達式模式“ [^az](man)[^az]
”捕獲了我想要的東西。
//String to search
"The man managed the football team"
//After using Regex.Replace I expect to see
"The coach managed the football team"
//But what I actually get is
"The coach coachaged the football team"
您需要\\b
另一個word boundary
。
\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)
使用\\bman\\b
參見演示。
https://regex101.com/r/yG7zB9/31
您的正則表達式將始終替換5
字符。 \\b
是一個0 width assertion
因此它不占用字符。
string strRegex = @"\bman\b";
Regex myRegex = new Regex(strRegex, RegexOptions.Multiline);
string strTargetString = @"The man managed the football team";
string strReplace = @"coach";
return myRegex.Replace(strTargetString, strReplace);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.