0

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?

0

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

C# does support the $1/$2 mechanism, but you're right about not capturing any groups. If you update your answer, I'll vote you up.
Ah yes, you are right. Not sure why I never realized that. Updated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.