简体   繁体   中英

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

I would like to extract some information from a string by regex, but the result is always None. The source code is as follows:

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

I want to extract content and property tuples, how can I fix it?

I would suggest something more suitable.

Using 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"]))

OUTPUT :

Content: Allrecipes
Property: og:site_name

The answer from @DirtyBit is better than using regex. But, if you still want to use regex, it may helps ( RegexDemo ):

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

Output:

('Allrecipes', 'og:site_name')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM