2010-11-10 53 views
0

我想創建一個基於正則表達式的替代文章,以自動將帖子中的嵌入式引用(其中許多)轉換爲適當的鏈接和標題格式。在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的最簡單方法是什麼?

回答

1

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

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); 
} 
+1

C#確實支持$ 1/$ 2機制,但你沒有捕獲任何組。如果您更新答案,我會爲您投票。 – jordanbtucker 2010-11-10 03:02:16

+0

啊,是的,你是對的。不知道爲什麼我從未意識到這一點。更新。 – cdhowie 2010-11-10 03:05:32

+0

謝謝@cdhowie :) – 2010-11-10 05:55:08