简体   繁体   中英

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.

Question : What is the easiest way to do convert the string #1 above to string #2 above?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM