Reputation: 4157
I'm trying to get a regular expression to replace all the links out of a text string for the value of the link.
A link may look like these:
<a href="http://whatever" id="an_id" rel="a_rel">the link</a>
<a href="/absolute_url/whatever" id="an_id" rel="a_rel">the link</a>
I want a regular expression that I get: the link
Upvotes: 15
Views: 39896
Reputation: 2840
I just added explicitly named groups:
<a.*href\s?=['"]*(?<href>[^'"]*)[^>]*>((?<text>(.(?!\<\/a\>))*.))<\/a>
https://regex101.com/r/sbtcYr/1
Upvotes: 1
Reputation: 1
I was not able to get any of the answers listed here to work...not sure they read your question right.
The way I read your post you're looking for the INBETWEEN of the <a href="abcdefg">example tag</a>
(aka extract "example tag")
However I managed to come up with this solution. It doesn't appear to work in all browsers though which is a bummer (aka edge, IE, haven't tried FF)
This link shows it working https://regexr.com/5dd0m
(?<=<a.*>).+(?=<\/a>)
Upvotes: 0
Reputation: 17831
/<a[^>]*>([^<]+)<\/a>/g
It's far from being perfect, but you need to provide more examples of what is a correct match and what isn't (e.g. what about whitespaces?)
Upvotes: 38
Reputation: 141
Just a little correction from the accepted answer. This is the correct regex: /<a[^>]*>([^<]+)<\/a>/g
. The forward slash (/)
for closing the anchor tag </a>
was not escaped so no match will be made.
Upvotes: 2
Reputation: 3619
/<a[\s]+([^>]+)>((?:.(?!\<\/a\>))*.)<\/a>/g
This one will match any <a ...>...</a>
tag including correctly matching ones that contain a < or any full tags such as:
blah blah <a href="test.html">This line contains an HTML opening < bracket.</a> blah blah
blah blah <a href="test.html">This line contains <strong>bold</strong> text.</a> blah blah
Would capture:
<a href="test.html">This line contains an HTML opening < bracket.</a>
href="test.html"
This line contains an HTML opening < bracket.
and
<a href="test.html">This line contains <strong>bold</strong> text.</a>
href="test.html"
This line contains <strong>bold</strong> text.
It also includes capturing groups for the tag attributes (like class="", href="", etc) and contain (what is between the tag) that can be removed if you do not need them.
If you want to capture across multiple lines add an "s" before or after the "g" flag at the end. Note that the "s" flag may not work in all flavors of regular expression.
Capture example (not using the "s" flag - not supported by regexr yet): http://regexr.com/39rsv
Upvotes: 24