要在通用字符串中查找 Web URL,您可以使用regular expression (regex)。
如下所示的用于 URL 匹配的简单正则表达式应该适合您的情况。
regex = r'('
# Scheme (HTTP, HTTPS, FTP and SFTP):
regex += r'(?:(https?|s?ftp):\/\/)?'
# www:
regex += r'(?:www\.)?'
regex += r'('
# Host and domain (including ccSLD):
regex += r'(?:(?:[A-Z0-9][A-Z0-9-]{0,61}[A-Z0-9]\.)+)'
# TLD:
regex += r'([A-Z]{2,6})'
# IP Address:
regex += r'|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
regex += r')'
# Port:
regex += r'(?::(\d{1,5}))?'
# Query path:
regex += r'(?:(\/\S+)*)'
regex += r')'
如果您想更加精确,在 TLD 部分,您应该确保 TLD 是有效的 TLD(在此处查看有效 TLD 的完整列表:https://data.iana.org/TLD/tlds-alpha-by-domain.txt):
# TLD:
regex += r'(com|net|org|eu|...)'
然后,您可以简单地编译以前的正则表达式并使用它来查找可能的匹配项:
import re
string = "This is a link http://www.google.com"
find_urls_in_string = re.compile(regex, re.IGNORECASE)
url = find_urls_in_string.search(string)
if url is not None and url.group(0) is not None:
print("URL parts: " + str(url.groups()))
print("URL" + url.group(0).strip())
如果是字符串 "This is a link http://www.google.com" 将输出:
URL parts: ('http://www.google.com', 'http', 'google.com', 'com', None, None)
URL: http://www.google.com
如果您使用更复杂的 URL 更改输入,例如 “这也是一个 URL https://www.host.domain.com:80/path/page.php?query=value&a2=v2#foo,但这不再是” 输出将是:
URL parts: ('https://www.host.domain.com:80/path/page.php?query=value&a2=v2#foo', 'https', 'host.domain.com', 'com', '80', '/path/page.php?query=value&a2=v2#foo')
URL: https://www.host.domain.com:80/path/page.php?query=value&a2=v2#foo
注意:如果您要在单个字符串中查找更多 URL,您仍然可以使用相同的正则表达式,但只需使用 findall() 而不是 search()。