How do I write a regex to grab links without link text?

How can I write a regex to replace links without link text like this:

<a href="http://www.somesite.com"></a>

      

from

<a href="http://www.somesite.com">http://www.somesite.com</a>

      

?

This is what I was trying to do to capture the matches, and this is not a trap. What am I doing wrong?

string pattern = "<a\\s+href\\s*=\\s*\"(?<href>.*)\">\\s*</a>";

      

+1


a source to share


4 answers


I could be wrong, but I think you just need to change the quantifier in the group href

to be lazy and not greedy.

string pattern = @"<a\s+href\s*=\s*""(?<href>.*?)"">\s*</a>";

      



(I also changed the type of the string literal to use @ for better readability.)

The rest of the regex seems fine to me. The fact that you are not collecting any matches makes me think otherwise, but there could be a problem in the rest of the code (or even in the original data - did you confirm that?).

+2


a source


I would not use regex - I would use Html Agility Pack and a query like:



foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[.='']")) {
    link.InnerText = link.GetAttribute("href");
}

      

+8


a source


I would suggest

string pattern = "(<a\\b[^>]*href=\"([^\"]+)\"[^>]*>)[\\s\\r\\n]*(</a>)";

      

This method also binds to its attribute href

elsewhere.

Replace

"$1$2$3"

      

The usual word of warning: HTML and regex are essentially incompatible. Use with caution, it may explode.

+1


a source


Mark Gravell has the correct answer, regexes are fundamentally bad at parsing HTML (see Can you give some examples of why parsing XML and HTML with regex is difficult? Why). See Can you give an example of parsing HTML with your favorite parser? for examples using various parsers.

0


a source







All Articles