Find string match pattern

2019-08-12 04:34发布

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条回答
Anthone
2楼-- · 2019-08-12 05:28
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')]
查看更多
登录 后发表回答