简体   繁体   中英

Python - find all URLs not surrounded by a tags already

Trying to figure out regex which detects URLs in text except those surrounded by <a href="url">...</a> already and surround them by tags.

input: "http://google.sk this is an url"
result: "<a href="http://google.sk">http://google.sk</a> this is an url"

input: "<a href="http://google.sk">http://google.sk</a> this is an url"
result: "<a href="http://google.sk">http://google.sk</a> this is an url"

This answer has helped me a lot but it does not expect already surrounded URLs.

def fix_urls(text):
    pat_url = re.compile(  r'''
                     (?x)( # verbose identify URLs within text
         (https|http|ftp|gopher) # make sure we find a resource type
                       :// # ...needs to be followed by colon-slash-slash
            (\w+[:.]?){2,} # at least two domain groups, e.g. (gnosis.)(cx)
                      (/?| # could be just the domain name (maybe w/ slash)
                [^ \n\r"]+ # or stuff then space, newline, tab, quote
                    [\w/]) # resource name ends in alphanumeric or slash
         (?=[\s\.,>)'"\]]) # assert: followed by white or clause ending
                         ) # end of match group
                           ''')

    for url in re.findall(pat_url, text):
       text = text.replace(url[0], '<a href="%(url)s">%(url)s</a>' % {"url" : url[0]})

    return text

If there is any <a> tag inside text, this function wraps it's URLs again which I don't want. Do you know how to make it work?

Use a negative lookbehind to check that href=" doesn't precede your URL (second line):

(?x) # verbose
(?<!href=\") #don't match already inside hrefs
(https?|ftp|gopher) # make sure we find a resource type
:// # ...needs to be followed by colon-slash-slash
((?:\w+[:.]?){2,}) # at least two domain groups, e.g. (gnosis.)(cx) fixed capture group*
(/?| # could be just the domain name (maybe w/ slash)
[^ \n\r\"]+ # or stuff then space, newline, tab, quote
[\w\/]) # resource name ends in alphanumeric or slash
(?=[\s\.,>)'\"\]]) # assert: followed by white or clause ending

https://regex101.com/r/EpcMKw/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM