Python Regex解决方案



我有一个字符串:

line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg, file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"

我想获得这样的结果:

[('https', 'dbwebb.se', ''), ('ftp', 'bth.com', '32'), ('file', 'localhost', '8585'), ('http', 'v2-dbwebb.se', '')]

我尝试了:

match = re.findall("([fh]t*ps?|file):[\/]*(.*?)(:d+|(?=[\/]))", line)

和我得到的:

[["https", "dbwebb.se", ""], ["ftp", "bth.com", ":32"], ["file", "localhost", ":8585"], ["http", "v2-dbwebb.se", ""]]

有一个差异,您可以SE":32"one_answers":8585"。我该怎么做才能获得" 32"one_answers" 8585"而不是愚蠢的":"thanx!

我建议

import re
line = line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg, file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"
match = re.findall(r"([fh]t*ps?|file)://([^/]*?)(?::(d+))?(?:/|$)", line)
print(match)

请参阅Python Demo

主要点是(?::(d+))?(?:/|$部分,其中:和1 数字部分是可选的((?...)?匹配1或0次),并且(?:/|$)/匹配或字符串的末端。

详细信息

  • ([fh]t*ps?|file)-第1组(元组中的第一项):
    • [fh]t*ps? -fh,零或更多tp和1或0 s S
    • |-或
    • file - file substring
  • ://-字面的子弦
  • ([^/]*?)-第2组(元组中的第二个项目):/以外的任何0或更多字符
  • (?::(d+))?-可选序列:
    • :- a col
    • (d+)-第2组(元组中的第三个项目):一个或多个数字
  • (?:/|$) -a :或字符串的末端。

REGEX不是解析URL的好工具,而是一个专用的库来完成此复杂的任务urllib:

from urllib.parse import urlparse
line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg, file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"
result = []
for i in line.split(', '):
    o = urlparse(i)
    result.append([o.scheme, o.hostname, o.port])

而不是正则表达式,为什么不在,上拆分,然后使用Python的urllib.parse.urlparse,例如:

from urllib.parse import urlparse
line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg, file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"
output = [urlparse(url) for url in line.split(', ')]

给你:

[ParseResult(scheme='https', netloc='dbwebb.se', path='/kunskap/uml', params='', query='', fragment='sequence'),
 ParseResult(scheme='ftp', netloc='bth.com:32', path='/files/im.jpeg', params='', query='', fragment=''),
 ParseResult(scheme='file', netloc='localhost:8585', path='/zipit', params='', query='', fragment=''),
 ParseResult(scheme='http', netloc='v2-dbwebb.se', path='/do%hack', params='', query='', fragment='')]

然后过滤出您想要的元素:

wanted = [(url.scheme, url.hostname, url.port or '') for url in output]

给您:

[('https', 'dbwebb.se', ''),
 ('ftp', 'bth.com', 32),
 ('file', 'localhost', 8585),
 ('http', 'v2-dbwebb.se', '')]

最新更新