gpt4 book ai didi

python - 如何在python中使用正则表达式检索数据?

转载 作者:太空宇宙 更新时间:2023-11-03 15:40:37 24 4
gpt4 key购买 nike

我有一个字符串定义为,

content = "f(1, 4, 'red', '/color/down1.html');    
f(2, 5, 'green', '/color/colorpanel/down2.html');
f(3, 6, 'blue', '/color/colorpanel/colorlibrary/down3.html');"

这是我尝试过的代码,但它不起作用:

results = re.findall(r"f(.*?)", content)
for each in results:
print each

如何使用正则表达式检索内容中的链接?谢谢。

最佳答案

您可以在 https://regex101.com/ 上学习基本的正则表达式和 http://regexr.com/

In [4]: import re

In [5]: content = "f(1, 4, 'red', '/color/down1.html'); \
...: f(2, 5, 'green', '/color/colorpanel/down2.html'); \
...: f(3, 6, 'blue', '/color/colorpanel/colorlibrary/down3.html');"

In [6]: p = re.compile(r'(?=/).*?(?<=.html)')

In [7]: p.findall(content)
Out[7]:
['/color/down1.html',
'/color/colorpanel/down2.html',
'/color/colorpanel/colorlibrary/down3.html']

.*? 匹配任何字符(除了行

*? 量词 - 匹配次数为零到无限次,尽可能少的次数,根据需要扩展(惰性)

您也可以只获取最后一个/

In [8]: p2 = re.compile(r'[^/]*.html')

In [9]: p2.findall(content)
Out[9]: ['down1.html', 'down2.html', 'down3.html']

[^/]* 匹配下面列表中不存在的单个字符

* 量词 - 匹配次数为零到无限次,尽可能多的次数,根据需要回馈(贪婪)

/ 匹配字符/字面意思(区分大小写)

. 匹配任何字符(行终止符除外)html 与字面上的字符 html 匹配(区分大小写)。

或者,您可以提取f()中的所有数据

In [15]: p3 = re.compile(r"(?=f\().*?(?<=\);)")

In [16]: p3.findall(content)
Out[16]:
["f(1, 4, 'red', '/color/down1.html');",
"f(2, 5, 'green', '/color/colorpanel/down2.html');",
"f(3, 6, 'blue', '/color/colorpanel/colorlibrary/down3.html');"]

关于python - 如何在python中使用正则表达式检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42173719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com