首页 > 解决方案 > 只输出匹配的正则表达式模式

问题描述

我有一个包含 10,000 行的 csv 文件。每行有 8 列。其中一列包含与此类似的文本:

this is a row:   http://somedomain.com | some_text | http://someanotherdomain.com | some_more_text
this is a row:   http://yetanotherdomain.net
this is a row:   https://hereisadomain.org | some_text

我目前正在以这种方式访问​​此列中的数据:

for row in csv_reader:
    the_url = row[3]

    # this regex is used to find the hrefs
    href_regex = re.findall('(?:http|ftp)s?://.*', the_url)
    for link in href_regex:
         print (link)

打印语句的输出:

http://somedomain.com | some_text | http://someanotherdomain.com | some_more_text
http://yetanotherdomain.net
https://hereisadomain.org | some_text

如何仅获取 URL?

http://somedomain.com
http://someanotherdomain.com 
http://yetanotherdomain.net
https://hereisadomain.org

标签: regexpython-3.xcsv

解决方案


只需将您的模式更改为:

\b(?:http|ftp)s?://\S+

不要用 匹配任何东西,而是用.*匹配任何非空白字符\S+。您可能还想在非捕获组之前添加一个单词边界。

检查它住在这里


推荐阅读