簡體   English   中英

.NET正則表達式查找包含文本

[英].NET regex expression to find enclosed text

我需要用標記語法替換所有出現在簡單標記中的字符串。 例如:我需要轉換看起來像這樣的字符串:

"this text needs to be displayed **bold**"

"**this** text **needs** to be displayed **bold**"

這些:

"this text needs to be displayed <bold>bold</bold>"

"<bold>this</bold> text <bold>needs</bold> to be displayed <bold>bold</bold>"

如果我使用以下內容:

string inputString = "this text needs to be displayed **bold**";
var reg = new Regex(@"\*\*([^\*]+)\*\*");
var outputString = reg.Replace(inputString, match => "<bold>" + match.Value + "</bold>");

輸出字符串如下所示:

"this text needs to be displayed <bold>**bold**</bold>"

換句話說, match.Value包括星號。

我確定了我可以使用的另一個正則表達式:

(?<=\*\*).+?(?=\*\*)

這將產生正確的第一場比賽,但對於隨后的比賽是錯誤的; 如上述代碼段中所使用的,對於第二個示例字符串,我得到以下匹配序列( match.Value ):

this
 text 
needs
 to be displayed
bold

它似乎返回的是每次出現在星號對之間的字符串,而不是根據需要將它們“配對”。

如果我使用諸如rubular之類的在線正則表達式工具,則我的初始解決方案似乎做對了(星號從匹配項中刪除),但這不是.NET實現返回的結果。

是否可以使用正則表達式字符串來獲得所需的結果,還是必須對匹配項進行一些后處理?

在替換呼叫中引用捕獲組。

var outputString = reg.Replace(inputString, "<bold>$1</bold>");

Ideone演示

有時,為了獲得更多控制權,我更喜歡使用使用MatchEvaluator委托的Regex.Replace重載版本:

Regex.Replace(input,
              @"\*\*(?<a>.*?)\*\*",
              m => string.Format("<bold>{0}</bold>", m.Groups["a"].Value))

盡管對於這樣一個簡單的任務:

Regex.Replace(input,
              @"\*\*(?<a>.*?)\*\*", 
              @"<bold>${a}</bold>")

就足夠了

暫無
暫無

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

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