【发布时间】:2018-11-11 17:41:34
【问题描述】:
我有一个包含 url 的 bytes 对象:
> body.decode("utf-8")
> 'https://www.wired.com/story/car-news-roundup-tesla-model-3-sales/\r\n\r\nhttps://cleantechnica.com/2018/11/11/can-you-still-get-the-7500-tax-credit-on-a-tesla-model-3-maybe-its-complicated/\r\n'
我需要将它拆分成一个列表,每个 url 作为一个单独的元素:
import re
pattern = '^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$'
urls = re.compile(pattern).split(body.decode("utf-8"))
我得到的是一个包含所有 url 的元素的列表:
['https://www.wired.com/story/car-news-roundup-tesla-model-3-sales/\r\n\r\nhttps://cleantechnica.com/2018/11/11/can-you-still-get-the-7500-tax-credit-on-a-tesla-model-3-maybe-its-complicated/\r\n']
如何将每个 url 拆分为单独的元素?
【问题讨论】:
-
为什么不用\s+分割呢?这应该会给你所需的结果。
-
@PushpeshKumarRajwanshi 你能举个例子吗?
-
这可能是因为你的模式不匹配任何东西,所以它没有分割任何东西。
-
你最好使用 findall() 之类的东西,使用你修改过的模式
(?m)^(?:https?:\/\/(?:www\.)?)?[a-z0-9]+(?:[\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(?::[0-9]{1,5})?(?:\/.*)?
标签: regex string list python-3.6