这个正则表达式有什么问题?
我正在尝试创建一个测试,来验证网页上是否显示了一个链接。
我不太明白我在这个断言测试中做错了什么:
self.assertRegexpMatches( response.content, r'<a href="/questions/?sort=elite" class="on" title="Staff Selected Questions">elite</a>')
我知道页面上有这个标记,因为我从响应内容中复制了它。
我试着在Python命令行中使用正则表达式:
In [27]: links = """<div class="tabsA"><a href="/questions/?sort=active" title="Most recently updated questions">active</a><a href="/questions/?sort=newest" title="most recently asked questions">newest</a><a href="/questions/?sort=hottest" title="most active questions in the last 24 hours">hottest</a><a href="/questions/?sort=mostvoted" title="most voted questions">most voted</a><a href="/questions/?sort=elite" class="on" title="Staff Selected Questions">elite</a></div>"""
In [28]: re.search(r'<a href="/questions/?sort=elite" class="on" title="Staff Selected Questions">elite</a>', links)
但不知为什么在那边也不管用。
我该怎么写正则表达式才能让它有效呢?
5 个回答
1
你应该对"?
"这个符号进行转义,因为在正则表达式中,这个符号有特别的含义。
>>> re.search(r'<a href="/questions/\?sort=elite" class="on" title="Staff Selected Questions">elite</a>', links)
4
你在正则表达式中看到的?
被当作一个可选的符号来理解了,这个符号的作用是表示前面的内容可以出现0次或1次。
比如说:<a href="/questions/?...
所以,程序在匹配的时候并没有找到字符串中的那个字面上的?
,而是把它当成了一个可选的/
来处理。在这种情况下,你需要用反斜杠来转义它,变成这样:
<a href="/questions/\?...
8
你为什么在这里用正则表达式呢?其实没有必要。你只是要匹配一个简单的字符串。可以直接使用:
self.assertContains(response, '<a href="/questions/?sort=elite" class="on" title="Staff Selected Questions">elite</a>')