1

I was wondering if something like this is possible with Regex, to replace a value ('John Doe' in my example below) with the first match ('[email protected]' in my example below):

Input:

Contact: <a href="mailto:[email protected]">John Doe</a>

Output:

Contact: [email protected]

Thanks in advance.

2
  • 2
    Yes, it is possible. however, your example is not clear. which part do you replace with what? As far as I can see, you just match and return some part of the string, there is no replace. Commented Mar 10, 2012 at 9:45
  • @AliFerhat I want to replace the name (John Doe) with the email address. Commented Mar 10, 2012 at 10:15

2 Answers 2

1

It would be something like this. The code will replace names with e-mails in all mailto links:

var html = new StringBuilder("Contact: <a href=\"mailto:[email protected]\">John1 Doe1</a> <a href=\"mailto:[email protected]\">John2 Doe2</a>");

var regex = new Regex(@"\<a href=\""mailto:(?<email>.*?)\""\>(?<name>.*?)\</a\>");
var matches = regex.Matches(html.ToString());

foreach (Match match in matches)
{
    var oldLink = match.Value;
    var email = match.Groups["email"].Value;
    var name = match.Groups["name"].Value;
    var newLink = oldLink.Replace(name, email);
    html = html.Replace(oldLink, newLink);
}

Console.WriteLine(html);

Output:

Contact: <a href="mailto:[email protected]">[email protected]</a> <a href="mailto:[email protected]">[email protected]</a>
Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately, I do need to "inject" the match rather than construct a new string, because the input is a large string with more text beyond what I've specified in the example.
@Nick, am I right understand that you have an HTML-page that can contain many "mailto" links and you want to replace them all?
If the HTML page is stored in a string object, then there is little chance to "inject", as the MSDN notes Strings are immutable--the contents of a string object cannot be changed after the object is created. Depending on how the HTML data is retrieved, you might consider a different approach.
0

Ok, got it working using MatchEvaluator delegate and named captures:

output = Regex.Replace(input, 
    @"\<a([^>]+)href\=.?mailto\:(?<mailto>[^""'>]+).?([^>]*)\>(?<mailtext>.*?)\<\/a\>", 
    m => m.Groups["mailto"].Value);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.