Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex matching links without <a> tag

(http([s]?):\/\/?)(([a-zA-Z0-9]+(\.?))+)([a-zA-Z0-9]+((\.[a-zA-Z]{2,5}){1,2})((\/[a-zA-Z0-9\?&=_\-\~:/?#[\]@!\$&'()\*\+,;]*)*)((\.[a-zA-Z]{2,5}){0,2}))

This is my regex which is working well for matching the links in the string. But I don't want it to select every link. If a link has "> before it, or </a> after it, that link shouldn't be mathced. How can it be done?

These should be matched:

adasdas http://www.stackoverflow.com asdasas
adasdasahttp://www.stackoverflow.com/something asdas

These should NOT be matched:

adasdas<a href="somelink">           http://www.stackoverflow.com     </a>asdasas
adasdasa<a href="somelink">http://www.stackoverflow.com/something</a> asdas

Why do I need this?: I want every link to be clickable even if it isn't between anchor tags.

like image 477
Wellenbrecher Avatar asked Jul 09 '14 10:07

Wellenbrecher


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is a good regex to match a URL?

@:%_\+~#= , to match the domain/sub domain name.

Does empty regex match everything?

An empty regular expression matches everything.

How do you match in regex?

Example : [^abc] will match any character except a,b,c . [first-last] – Character range: Matches any single character in the range from first to last.


2 Answers

With all the disclaimers about using regex to parse html, if you want to use regex for this task, this will work:

$regex="~<a.*?</a>(*SKIP)(*F)|http://\S+~";

See the demo.

This problem is a classic case of the technique explained in this question to "regex-match a pattern, excluding..."

The left side of the alternation | matches complete <a ...tags </a> then deliberately fails, after which the engine skips to the next position in the string. The right side matches the urls, and we know they are the right ones because they were not matched by the expression on the left.

The url regex I put on the right and can be refined, just use whatever suits your needs.

Reference

  • How to match (or replace) a pattern except in situations s1, s2, s3...
  • Article about matching a pattern unless...
like image 118
zx81 Avatar answered Sep 22 '22 04:09

zx81


You need to add lookarounds to your regex c.f.:

  • Regular expression negative lookahead
  • Lookahead and Lookbehind Zero-Length Assertions
like image 43
Valerij Avatar answered Sep 19 '22 04:09

Valerij