简体   繁体   English

C#中的多个正则表达式替换

[英]Multiple Regex Replacements in C#

I am trying create a Regex-based replacement for an article to automatically convert embedded references (many of them) in posts into the appropriate link and title format. 我正在尝试为文章创建一个基于正则表达式的替代品,以将帖子中的嵌入引用(其中很多)自动转换为适当的链接和标题格式。

For example, given this: 例如,鉴于此:

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 want to get this: ...我想得到这个:

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.

I currently have this: 我目前有这个:

/* 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);
}

But it seems to return lines that contain <a href='/post/'></a> without appending matches instead of $1 and $2. 但是它似乎返回的行包含<a href='/post/'></a>而不附加匹配项,而不是$ 1和$ 2。

Question : What is the easiest way to do convert the string #1 above to string #2 above? 问题 :将上面的字符串#1转换为上面的字符串2的最简单方法是什么?

You're not capturing the parts of the expression you want to extract. 您没有捕获要提取的表达式的各个部分。 Try something like this: 尝试这样的事情:

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