views:

111

answers:

3

Could anyone be able to give a regular expressiont to match the link text between <a> and </a> tags in a HTML snippet.

Sample data: <a href="link.html">Link Title</a> - 15 comments <br/> <a href="otherlink.html">Some other Title</a> - 6 comments

Requirement: I need to extract only the link texts (i.e. the one between <a> and </a> - Link Title and Some other Title) to use in my application.

Please note that the link text might contain non-english characters and all possible puncutations also. I tried using '.' operator, but since it does a greedy match, it matches the entire text between first <a> and last </a>. But I want only the link texts.

Any help?

+2  A: 

Try

<a[^>]+>(.*?)</a>
S.Mark
Ryan Graham
Yes, right, but even parsers can breakable with crafted invalid html too.
S.Mark
But this isn't invalid HTML. It's perfectly valid.
Jörg W Mittag
+3  A: 

Stop using regex to 'parse' html.

http://www.codinghorror.com/blog/archives/001311.html

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454

Go use a real parser.

http://java-source.net/open-source/html-parsers

Andrew Kuklewicz
I say that with love, tough love.
Andrew Kuklewicz
i have written my own parsing logic in a conventional way (substring, indexOf, etc) - but it's a requirement to use the regular expression. :(
Veera
A requirement to use a regex? ok. Well, the link above has plenty of excellent parsers, please don't write your own, and here is example code to parse out URLs from anchor tags from about 4 of them: http://www.benmccann.com/dev-blog/java-html-parsing-library-comparison/
Andrew Kuklewicz
A: 

This has been discussed literally dozens of times already on StackOverflow (and thousands of times in other fora), but apparently it still needs repeating: it can't be done.

Regular Expressions can only parse Regular Languages. HTML is not a Regular Language. Proving that you cannot parse HTML with Regular Expressions is a regular (pun intended) homework assignment on pretty much every college and university on the planet. It has been proven by literally tens of thousands of people. It is as watertight as any mathematical proof can be. It is a very short, very simple, very approachable proof. There is no way that anyone will be able to find a hidden flaw in it, because the proof is so simple and small that there is plainly nowhere a flaw could hide.

Oh, and did I mention it can't be done?

This is not the Traveling Salesman Problem, where it takes a very long time to run. It is not P=NP, where we don't know whether it is true or not.

This is genuinely, absolutely, 100%, positively, totally, provably impossible.

I forgot. Did I already mention it can't be done?

Jörg W Mittag