Regular expression to match text between <a ..> and </a>
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 Tit开发者_运维百科le 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?
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
Try
<a[^>]+>(.*?)</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?
精彩评论