如何确保re.findall()在正确的位置停止?

8 python regex findall python-2.7

这是我的代码:

a='<title>aaa</title><title>aaa2</title><title>aaa3</title>'
import re
re.findall(r'<(title)>(.*)<(/title)>', a)
Run Code Online (Sandbox Code Playgroud)

结果是:

[('title', 'aaa</title><title>aaa2</title><title>aaa3', '/title')]
Run Code Online (Sandbox Code Playgroud)

如果我设计了一个爬虫来获取网站的标题,我可能会得到这样的东西,而不是网站的标题.

我的问题是,我如何限制findall单身<title></title>

Jon*_*nts 13

如果您只想要一个匹配,请使用re.search而不是re.findall:

>>> s = '<title>aaa</title><title>aaa2</title><title>aaa3</title>'
>>> import re
>>> re.search('<title>(.*?)</title>', s).group(1)
'aaa'
Run Code Online (Sandbox Code Playgroud)

如果您想要所有标签,那么您应该考虑将其更改为非贪婪(即 - .*?):

print re.findall(r'<title>(.*?)</title>', s)
# ['aaa', 'aaa2', 'aaa3']     
Run Code Online (Sandbox Code Playgroud)

但是真的考虑使用BeautifulSoup或lxml或类似解析HTML.

  • 确实,使用regexen来解析HTML或XML通常是一个坏主意. (3认同)

Chi*_*den 5

改为使用非贪婪的搜索:

r'<(title)>(.*?)<(/title)>'
Run Code Online (Sandbox Code Playgroud)

问号表示尽可能少地匹配字符.现在你的findall()将返回你想要的每个结果.

http://docs.python.org/2/howto/regex.html#greedy-versus-non-greedy


zha*_*gyu 2

re.findall(r'<(title)>(.*?)<(/title)>', a)
Run Code Online (Sandbox Code Playgroud)

?在 后面添加一个*,这样它将是非贪婪的。