Python正则表达式后向需要固定宽度模式


问题内容

尝试提取html页面的标题时,我一直使用以下正则表达式:

(?<=<title.*>)([\s\S]*)(?=</title>)

这将提取文档中标签之间的所有内容,而忽略标签本身。但是,当尝试在Python中使用此正则表达式时,会引发以下异常:

Traceback (most recent call last):  
File "test.py", line 21, in <module>
    pattern = re.compile('(?<=<title.*>)([\s\S]*)(?=</title>)')
File "C:\Python31\lib\re.py", line 205, in compile
    return _compile(pattern, flags)   
File "C:\Python31\lib\re.py", line 273, in _compile
    p = sre_compile.compile(pattern, flags)   File
"C:\Python31\lib\sre_compile.py", line 495, in compile
    code = _code(p, flags)   File "C:\Python31\lib\sre_compile.py", line 480, in _code
_compile(code, p.data, flags)   File "C:\Python31\lib\sre_compile.py", line 115, in _compile
    raise error("look-behind requires fixed-width pattern")
sre_constants.error: look-behind requires fixed-width pattern

我使用的代码是:

pattern = re.compile('(?<=<title.*>)([\s\S]*)(?=</title>)')
m = pattern.search(f)

如果我做了一些最小的调整,它将起作用:

pattern = re.compile('(?<=<title>)([\s\S]*)(?=</title>)')
m = pattern.search(f)

但是,这将不考虑由于某种原因具有属性或类似属性的潜在html标题。

有人知道这个问题的解决方法吗?任何提示表示赞赏。


问题答案:

如果您只想获取标题标签,

html=urllib2.urlopen("http://somewhere").read()
for item in html.split("</title>"):
    if "<title>" in item:
        print item[ item.find("<title>")+7: ]