我正在尝试为文章创建一个基于正则表达式的替换,以自动将帖子中的嵌入引用(其中许多)转换为适当的链接和标题格式。
例如,鉴于此:
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的最简单方法是什么?
答案 0 :(得分: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);
}