2

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?

Veera
  • 32,532
  • 36
  • 98
  • 137
  • 2
    See http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 ;-) – Asher Dunn Jan 19 '10 at 06:11

3 Answers3

6

Stop using regex to 'parse' html.

https://blog.codinghorror.com/parsing-html-the-cthulhu-way/

RegEx match open tags except XHTML self-contained tags

Go use a real parser.

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Andrew Kuklewicz
  • 10,621
  • 1
  • 34
  • 42
  • 1
    I say that with love, tough love. – Andrew Kuklewicz Jan 19 '10 at 06:16
  • 1
    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 Jan 19 '10 at 06:22
  • 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 Jan 19 '10 at 06:31
2

Try

<a[^>]+>(.*?)</a>
YOU
  • 120,166
  • 34
  • 186
  • 219
0

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
  • 363,080
  • 75
  • 446
  • 653