我有一個來自外部源的字串,其中包含重要文本周圍的開始和結束標記(兩個星號)。我在一個 html 檔案中顯示這個文本,我需要先決議字串C#并用粗體顯示任何標記的文本,包括標記。
希望下面的內容顯示了我正在努力實作的目標......
public static void Main()
{
string orginalText = "Cat dog ** monkey ** lizard hamster ** fish ** frog";
Console.WriteLine(ReplaceMarkedText(orginalText));
}
string ReplaceMarkedText(string text)
{
// This is the closest I've gotten so far, but it only works with one pair of asterisks.
var matches = Regex.Match(text, @"\*\*([^)]*)\*\*").Groups;
string newText = text.Replace("**", string.Empty);
foreach (Group match in matches)
{
if (match.Value.Length > 0)
{
newText = newText.Replace(match.Value, "<b>**" match.Value "**</b>");
}
}
return newText;
}
我想在控制臺輸出中看到的內容: Cat dog <b>** monkey **</b> lizard hamster <b>** fish **</b> frog
uj5u.com熱心網友回復:
用
string Result = Regex.Replace(text, "\\*{2}.*?\\*{2}", "<b>$&</b>");
請參閱正則運算式證明。
解釋
NODE EXPLANATION
--------------------------------------------------------------------------------
\*{2} '*' (2 times)
--------------------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
\*{2} '*' (2 times)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/361852.html
