简体   繁体   中英

Find string match pattern

I have a pattern like this:

pattern = "Delivered to %(recipient)s at %(location)s"

How can I get the recipient and location of a string based on this pattern?

For example: Delivered to Mr.Smith at Seattle would be extracted to [Mr.Smith,Seattle] .

Hence, I want that any string that matches this pattern will extract these 2 parameters like this.

import re

pattern = 'Delivered to Mr.Smith at Seattle'

re.match(r'Delivered to (.*) at (.*)', pattern).groups()
('Mr.Smith', 'Seattle')

re.findall(r'Delivered to (.*) at (.*)', pattern)
[('Mr.Smith', 'Seattle')]

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