[英]How to perform multiple Regex replacements in sequence from a list of unique items cleanly in 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.