Regex reemplaza el valor con la primera coincidencia

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 ('' in my example below):


Contact: <a href="">John Doe</a>



Gracias de antemano.

preguntado el 10 de marzo de 12 a las 09:03

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. -

@AliFerhat I want to replace the name (John Doe) with the email address. -

2 Respuestas

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

var html = new StringBuilder("Contact: <a href=\"\">John1 Doe1</a> <a href=\"\">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);



Contact: <a href=""></a> <a href=""></a>

respondido 10 mar '12, 10:03

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

@Nick, am I right understand that you have an HTML-page that can contain many "mailto" links and you want to replace them all? - kyrylo m

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. - jcodificador

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

output = Regex.Replace(input, 
    m => m.Groups["mailto"].Value);

respondido 11 mar '12, 06:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.