我正在尋找一個正則運算式來實作一個搜索和替換方法,該方法在較長的文本中識別像“/Sample Text:”這樣的字串(例如“這是一個/Sample Text:在一個句子中”),其中“匹配整個單詞” ' 和/或 '匹配大小寫' 可以指定。我是正則運算式的新手。非常感謝。
我嘗試了類似下面的方法,但這不是我所期望的:
var text = "This is a /Sample Text: in a sentence";
var oldValue = "/Sample Text:";
var newValue = "sample text";
var result = Regex.Replace(text, $"\\b{oldValue}{(char.IsPunctuation(newValue[newValue.Length - 1]) ? "(?!\\" newValue[newValue.Length - 1] ")" : string.Empty)}", newValue, RegexOptions.CultureInvariant);
uj5u.com熱心網友回復:
看起來“單詞”可以在“單詞”內的任何位置包含任何特殊字符。在這種情況下,您需要
- 逃避
oldValue“話” - 使用動態自適應詞邊界。
請參閱示例 C# 演示:
var text = "This is a /Sample Text: in a sentence";
var oldValue = "/Sample Text:";
var newValue = "sample text";
var matchCase = RegexOptions.IgnoreCase;
var result = Regex.Replace(text, $@"(?!\B\w){Regex.Escape(oldValue)}(?<!\w\B)", newValue, matchCase);
result值為This is a sample text in a sentence。_
(?!\B\w){Regex.Escape(oldValue)}(?<!\w\B)手段_
(?!\B\w)- 僅當后面的 char 是單詞 char 時才以單詞邊界開頭的位置{Regex.Escape(oldValue)}- 一個內插字串變數,它是一個轉義值oldValue(?<!\w\B)- 僅當前面的 char 是單詞 char 時才跟隨單詞邊界的位置。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/437271.html
下一篇:排序int[]陣列
