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

2024-10-01 13:27:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串定义为

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

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


Tags: 字符串定义htmlgreenblueredcontentresults
3条回答

你可以这样尝试:

import re

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');"""

print re.findall(r"(\/[^']+?)'", content)

输出:

['/color/down1.html', '/color/colorpanel/down2.html', '/color/colorpanel/colorlibrary/down3.html']  

正则表达式:

(\/[^']+?)'匹配/,后跟一个或多个非'字符,直到第一次出现'并在group1中捕获。你知道吗

你可以这样做:

re.findall(r"f\(.*,.*,.*, '(.*)'", content)

您可以在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']

*?匹配任何字符(行除外)

*?量词-在零次和无限次之间进行匹配,尽可能少的匹配次数,根据需要进行扩展(lazy)

你也可以得到最后的/

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');"]

相关问题 更多 >