簡體   English   中英

C#中的多個正則表達式替換

[英]Multiple Regex Replacements in C#

我正在嘗試為文章創建一個基於正則表達式的替代品,以將帖子中的嵌入引用(其中很多)自動轉換為適當的鏈接和標題格式。

例如,鑒於此:

I have already blogged about this topic ((MY TOPIC ID: "2324" "a number of times")) before.   And I have also covered ((MY TOPIC ID: "777" "similar topics")) in the past.

...我想得到這個:

I have already blogged about this topic <a href='/post/2324'>a number of times</a> before.   And I have also covered <a href='/post/777'>similar topics</a> in the past.

我目前有這個:

/* Does not work */
public static string ReplaceArticleTextWithProductLinks(string input)
{
    string pattern = "\\(\\(MY TOPIC ID: \\\".*?\\\" \\\".*?\\\"\\)\\)";
    string replacement = "<a href='/post/$1'>$2</a>";

    return Regex.Replace(input, pattern, replacement);
}

但是它似乎返回的行包含<a href='/post/'></a>而不附加匹配項,而不是$ 1和$ 2。

問題 :將上面的字符串#1轉換為上面的字符串2的最簡單方法是什么?

您沒有捕獲要提取的表達式的各個部分。 嘗試這樣的事情:

public static string ReplaceArticleTextWithProductLinks(string input)
{
    string pattern = @"\(\(MY TOPIC ID: ""(.*?)"" ""(.*?)""\)\)";
    string replacement = "<a href='/post/$1'>$2</a>";

    return Regex.Replace(input, pattern, replacement);
}

暫無
暫無

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

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