Python: 正则匹配Url

Author Avatar
云璃 2019年10月10日
import re


def find_all_url(sentence, show_urls = None, delete_urls = None):
    r = re.compile(r'(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))')
    url_list = r.findall(sentence)
    if show_urls == 1:
        print "find", str(len(url_list)), "URLs"
        for i in url_list:
            print i[0]

    if delete_urls == 1:
        for j in url_list:
            # sentence = sentence.replace(j[0], '<URL>')
            sentence = sentence.replace(j[0], '')
        return sentence
    return 1

http://daringfireball.net/2010/07/improved_regex_for_matching_urls

本文链接:https://www.masterzc.cn/archives/128.html
本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处

Title - Artist
0:00