Find string match pattern

2019-08-12 05:12发布

问题:

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.

回答1:

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