【问题标题】:Python regex matching URLsPython 正则表达式匹配 URL
【发布时间】:2021-12-31 18:21:51
【问题描述】:

我在 URL 的文本文件中有一个列表,其中包含一些不需要的文本下面的例子:

文件内容是一个 URL 列表:

http://www.example.com/52                   (Status: 403) [Size: 919]
http://www.example.com/details              (Status: 403) [Size: 919]
http://www.example.com/h                    (Status: 403) [Size: 919]
http://www.example.com/affiliate            (Status: 403) [Size: 919]
http://www.example.com/56                   (Status: 403) [Size: 919]

我使用的正则表达式是:"^[://.a-zA-Z0-9-_]*"

输出如下:

['http://www.example.com/52']
['http://www.example.com/details']
['http://www.example.com/h']
['http://www.example.com/affiliate']
['http://www.example.com/56']

我需要输出如下:

http://www.example.com/52
http://www.example.com/details
http://www.example.com/h
http://www.example.com/affiliate
http://www.example.com/56

本程序使用的代码如下:

import re

with open("test.txt","r") as test:
    for i in test:
        x = re.findall("^[://.a-zA-Z0-9-_]*",i)
        print(x)

【问题讨论】:

  • 也许print(x[0]) 就是你要找的。​​span>
  • 这是工作谢谢你 j1-lee
  • 不使用regex也可以像url = i.split()[0]一样应用

标签: python python-3.x regex url re


【解决方案1】:

findall 生成一个字符串列表,您可以打印出结果中的第一个元素 print(x[0]) 或只使用 match 代替此用例,因为每行有 1 个 url。

with open("test.txt","r") as test:
    for i in test:
        x = re.match(r"[://.a-zA-Z0-9-_]*", i)
        print(x.group(0))

【讨论】:

    猜你喜欢
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 2016-12-12
    • 2012-02-04
    相关资源
    最近更新 更多