2011-06-03 63 views
0

我正在尝试创建一个测试来验证链接是否在网页上呈现。这个正则表达式有什么问题?

我不明白我在做什么错了这一说法测试:

self.assertRegexpMatches(response.content, r'<a href="https://stackoverflow.com/questions/?sort=elite" class="on" title="Staff Selected Questions">elite</a>') 

我知道的标记在页面上,因为我是从response.content

我试图复制它在Python外壳中使用正则表达式:

In [27]: links = """<div class="tabsA"><a href="https://stackoverflow.com/questions/?sort=active" title="Most recently updated questions">active</a><a href="https://stackoverflow.com/questions/?sort=newest" title="most recently asked questions">newest</a><a href="https://stackoverflow.com/questions/?sort=hottest" title="most active questions in the last 24 hours">hottest</a><a href="https://stackoverflow.com/questions/?sort=mostvoted" title="most voted questions">most voted</a><a href="https://stackoverflow.com/questions/?sort=elite" class="on" title="Staff Selected Questions">elite</a></div>""" 

In [28]: re.search(r'<a href="https://stackoverflow.com/questions/?sort=elite" class="on" title="Staff Selected Questions">elite</a>', links) 

由于某种原因,它不工作。

如何创建正则表达式使其起作用?

+0

你必须逃避问号。所以它的re.search(r'somestuff \?somemorestuff') – PeterT 2011-06-03 20:23:58

+5

舌头在脸颊响应:它是什么错是你试图使用正则表达式来解析标记。 ;-) – 2011-06-03 20:24:18

回答

0

The?字符是一个特殊的RegEx字符,必须转义。

后续的正则表达式将工作

<a href="https://stackoverflow.com/questions/\?sort=elite" class="on" title="Staff Selected Questions">elite</a> 

注意\前?

为瞎搞与正则表达式的一个很好的工具可以在这里找到:

http://regexpal.com/

它可以节省非常多的时间和头痛...

+0

个人而言,我更喜欢expresso – CaffGeek 2011-06-03 20:29:26

4

在你的正则表达式的?是得到解释为? quantifier(该部分的结束):

<a href="https://stackoverflow.com/questions/?...

因此,引擎永远不会匹配出现在字符串中的文字?,而是在该位置匹配可选的/。与像这样反斜杠转义:

<a href="https://stackoverflow.com/questions/\?...

1

你应该逃脱“?”,因为该符号对正则表达式特殊的意义。

>>> re.search(r'<a href="https://stackoverflow.com/questions/\?sort=elite" class="on" title="Staff Selected Questions">elite</a>', links) 
-1

这可能是“<”和“>”字符。在一些正则表达式语法中,它们是指示行的开始和结束的特殊字符。

您可能会看到一个regular expression tester工具来帮助您了解它们。

+1

'<' and '>'在Python中没有特殊含义,除非它们用于命名捕获组“(?P ...)'(或者,另外,'<'用于lookbehind语法'(?<...)'和'(?<!...)')。 – eldarerathis 2011-06-03 20:31:48

8

你为什么在这里使用正则表达式?绝对没有理由。你只是匹配一个简单的字符串。使用方法:

self.assertContains(response, '<a href="https://stackoverflow.com/questions/?sort=elite" class="on" title="Staff Selected Questions">elite</a>') 
相关问题