python正则表达式匹配空格或没有

时间:2015-04-03 11:15:35

标签: python regex

我需要一个匹配空格或没有任何内容的正则表达式。我使用它来查找包含HTML代码的字符串中的类。

现在我的模式看起来:

pattern = r'class="([A-Za-z0-9_\./\\-]*)"'

但它没有捕捉到'class ='一些类名“' 感谢您的帮助。谢谢。

1 个答案:

答案 0 :(得分:2)

最好使用HTML Parser,BeautifulSoup

from bs4 import BeautifulSoup
soup = BeautifulSoup(url)
print soup.find_all(tag_name, class_name)

演示:

>>> html_doc = """
<html><head><title>The Dormouse's story</title></head>

<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and  their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""
>>> soup = BeautifulSoup(html_doc)
>>> soup.find_all('p', 'title')
[<p class="title"><b>The Dormouse's story</b></p>]
>>> soup.find_all('a')
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
相关问题