Find string match pattern

白昼怎懂夜的黑 提交于 2019-12-11 09:59:18

问题


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


来源:https://stackoverflow.com/questions/34460231/find-string-match-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!