簡體   English   中英

用正則表達式提取子串,總是沒有 re.match()

[英]Extract substring with regular expression, always None of re.match()

我想通過正則表達式從字符串中提取一些信息,但結果始終為 None。 源代碼如下:

line = '<meta content=\"Allrecipes\" property=\"og:site_name\"/>'
x = re.match(r'property=".+?"',line)
print(x)

我想提取內容和屬性元組,我該如何解決?

我會建議更合適的東西。

使用beautifulsoup

from bs4 import BeautifulSoup

line = '<meta content=\"Allrecipes\" property=\"og:site_name\"/>'
soup = BeautifulSoup(line, 'lxml')

print("Content: {}".format(soup.meta["content"]))
print("Property: {}".format(soup.meta["property"]))

輸出

Content: Allrecipes
Property: og:site_name

@DirtyBit 的答案比使用正則表達式要好。 但是,如果您仍然想使用正則表達式,它可能會有所幫助( RegexDemo ):

line = '<meta content=\"Allrecipes\" property=\"og:site_name\"/>'
regex = re.search("content=\\\"(?P<content>.*)\\\".*property=\\\"(?P<prop>.*)\\\"\/>",line)
print (regex.groups())

輸出:

('Allrecipes', 'og:site_name')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM