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>";
a source to share
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?).
a source to share
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");
}
a source to share
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.
a source to share