【问题标题】:Want to get part of string using regular expression想要使用正则表达式获取字符串的一部分
【发布时间】:2012-09-28 18:56:14
【问题描述】:

我有一个字符串:

 <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>'''

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

【问题讨论】:

  • 将第一个(.*) 更改为(.*?),然后只需执行MatchObject.groups(1)。您可能想重新阅读 python re 文档。
  • 你也可以只做s.split('&gt;',1)[1][:-4] - 尽量不要使用正则表达式来解析HTML。
  • 如果您只想要字符串的最后一部分而不是为什么在第一个 .* 周围使用 brackets。在正则表达式中,() 用于捕获您想要的字符串。因此,如果您只想提取最后一部分,请尝试pattern = '''&lt;a class="x3-large" .*"&gt;(.*)&lt;/a&gt;'''。另请阅读 greedy and non-greedy 正则表达式量词。

标签: python regex string url


【解决方案1】:

本着回答你应该问的问题的精神 ;^),是的,你应该使用 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>]

【讨论】:

【解决方案2】:

输入([^"]*) 代替第一个(.*)([^&lt;]*) 代替第二个。或者使用非贪婪的量词,如(.*?)

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 2021-09-27
    • 1970-01-01
    • 2011-07-12
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    相关资源
    最近更新 更多