想要使用正则表达式获取字符串的一部分

时间:2012-09-28 18:56:15

标签: python regex string url

我有一个字符串:

 <a class="x3-large" href="_ylt=Ats3LonepB5YtO8vbPyjYAWbvZx4;_ylu=X3oDMTVlanQ4dDV1BGEDMTIwOTI4IG5ld3MgZGFkIHNob290cyBzb24gdARjY29kZQNwemJ1ZmNhaDUEY3BvcwMxBGVkAzEEZwNpZC0yNjcyMDgwBGludGwDdXMEaXRjAzAEbWNvZGUDcHpidWFsbGNhaDUEbXBvcwMxBHBrZ3QDMQRwa2d2AzI1BHBvcwMyBHNlYwN0ZC1mZWEEc2xrA3RpdGxlBHRlc3QDNzAxBHdvZQMxMjc1ODg0Nw--/SIG=12uht5d19/EXP=1348942343/**http%3A//news.yahoo.com/conn-man-kills-masked-teen-learns-son-063653076.html"  style="font-family: inherit;">Man kills masked teen, learns it&#39;s his son</a>

我想只得到它的最后一部分,实际信息:

Man kills masked teen, learns it&#39;s his son

到目前为止,我做了类似的事情:

pattern = '''<a class="x3-large" (.*)">(.*)</a>'''

但它没有做我想要的,第一个(.*)匹配链接中的所有废话,但第二个是我想要的实际消息

2 个答案:

答案 0 :(得分:2)

本着回答问题的精神,你应该问过; ^),是的,你应该使用BeautifulSoup [link]或lxml或真正的解析器来处理HTML。例如:

>>> s = '<a class="x3-large" href="_stuff--/SIG**morestuff" style="font-family: inherit;">Man learns not to give himself headaches using regex to deal with HTML</a>'
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(s)
>>> soup.get_text()
u'Man learns not to give himself headaches using regex to deal with HTML'

或者如果要捕获多个文本:

>>> s = '<a class="test" href="ignore1">First sentence</a><a class="test" href="ignore1">Second sentence</a>'
>>> soup = BeautifulSoup(s)
>>> soup.find_all("a")
[<a class="test" href="ignore1">First sentence</a>, <a class="test" href="ignore1">Second sentence</a>]
>>> [a.get_text() for a in soup.find_all("a")]
[u'First sentence', u'Second sentence']

或者,如果您只想要class的某些值:

>>> s = '<a class="test" href="ignore1">First sentence</a><a class="x3-large" href="ignore1">Second sentence</a>'
>>> soup = BeautifulSoup(s)
>>> soup.find_all("a", {"class": "x3-large"})
[<a class="x3-large" href="ignore1">Second sentence</a>]

答案 1 :(得分:1)

键入([^"]*)而不是第一个(.*)([^<]*)而不是第二个(.*?)。或者使用非贪婪量词,如{{1}}。