Python需要正则表达式的帮助吗

2024-04-25 05:35:01 发布

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

我自己搜索过了,但无法成功地生成正则表达式

我有一个html文件,其中包含[]之间的变量,我想获取这些变量中的每个单词

<div id='client_info'>
    <p><b>[client_name]</b><br/><b>[client_company]</b></p>
    <p>[client_address]<br/>[client_CP]<br/>[client_city]</p>
</div>

在那里它应该给我一个数组,包含“client\u name”,“client\u company”,“client\u address”

我做过:

vars = re.search('\[(.*)\]', html_template)
groups = vars.groups()
print groups

但是它输出('client_name]</b><br/><b>[client_company',)

我试过玩^$,但没有成功

谢谢你的帮助


Tags: 文件namebrdivinfoclientidcity
2条回答

Python有一个非常强大的库,名为BeautifulSoup。我建议您使用这个来解析html。所以我建议您首先使用这个库来解析div。然后执行正则表达式

html = '''
...some htmls...
<div id='client_info'>
    <p><b>[client_name]</b><br/><b>[client_company]</b></p>
    <p>[client_address]<br/>[client_CP]<br/>[client_city]</p>
</div>
...more htmls...
'''
soup = BeautifulSoup(html)
div = soup.find("div", {"id":"client_info"})
p = div.findAll("p")
for tag in p:
    print re.findall('\[([^\]]*)\]', tag.renderContents())

可能有一种方法可以用BeautifulSoup解析<br/>,但我不知道

或者使用非贪婪量词,如下所示:

re.search('\[(.*?)\]', html_template)

或者一个字符类,比如:

re.search('\[([^\]]*)\]', html_template)

并使用^{}获取所有匹配的子字符串

相关问题 更多 >