import re
import urllib
p = urllib.urlopen("http://sprunge.us/QZhU")
page = p.read()
pos = page.find("<h2><span>")
print page[pos:pos+48]
c = re.compile(r'<h2><span>(.*)</span>')
print c.match(page).group(1)
当我运行它时:
shadyabhi@archlinux $ python2 temp.py
<h2><span>House.S08E02.HDTV.XviD-LOL.avi</span>
Traceback (most recent call last):
File "temp.py", line 8, in <module>
print c.match(page).group(1)
AttributeError: 'NoneType' object has no attribute 'group'
shadyabhi@archlinux $
如果我可以使用 string.find 找到一个字符串,那么当我使用正则表达式时会出现什么问题。我试过寻找 http://docs.python.org/howto/regex.html#regex-howto但没有帮助。
最佳答案
match
只匹配字符串的开头。使用 search
, finditer
或 findall
.
另请注意 *
是贪婪的。您可能希望将正则表达式更改为 r'<h2><span>(.*?)</span>'
.
总而言之,以下对我有用:
import re
import urllib
p = urllib.urlopen("http://sprunge.us/QZhU")
page = p.read()
pos = page.find("<h2><span>")
print page[pos:pos+48]
c = re.compile(r'<h2><span>(.*?)</span>')
print c.search(page).group(1)
关于python - 无法使用正则表达式从字符串中找到数据,而 string.find() 工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7768157/