我需要匹配所有这些开始标记:
<p>
<a href="foo">
Run Code Online (Sandbox Code Playgroud)
但不是这些:
<br />
<hr class="foo" />
Run Code Online (Sandbox Code Playgroud)
我想出了这个,并希望确保我做对了.我只抓住了a-z.
<([a-z]+) *[^/]*?>
Run Code Online (Sandbox Code Playgroud)
我相信它说:
/,然后我有这个权利吗?更重要的是,你怎么看?
为了响应Python 正则表达式,我尝试使用以下方法实现 HTML 解析器HTMLParser:
import HTMLParser
class ExtractHeadings(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.text = None
self.headings = []
def is_relevant(self, tagname):
return tagname == 'h1' or tagname == 'h2'
def handle_starttag(self, tag, attrs):
if self.is_relevant(tag):
self.in_heading = True
self.text = ''
def handle_endtag(self, tag):
if self.is_relevant(tag):
self.headings += [self.text]
self.text = None
def handle_data(self, data):
if self.text != None:
self.text += data
def handle_charref(self, name):
if self.text != None:
if name[0] == 'x':
self.text += chr(int(name[1:], 16)) …Run Code Online (Sandbox Code Playgroud)