嗨简单问题......
我想找到与以下模式基本匹配的所有字符串:
/team/*/Euro_2012
所以它应该找到:
/team/Croatia/Euro_2012
/team/Netherlands/Euro_2012
但不是:
/team/Netherlands/WC2014
如何使用re.compile
在Regex for Python中编写此代码?
答案 0 :(得分:2)
足够简单:
re.findall(r'/team/.*?/Euro_2012', inputtext)
您可能希望限制/team/
和/Euro_2012
之间的允许字符,以减少较大文本中误报的可能性:
re.findall(r'/team/[\w\d%.~+-/]*?/Euro_2012', inputtext)
演示:
>>> import re
>>> sample = '''\
... /team/Croatia/Euro_2012
... /team/Netherlands/Euro_2012
... /team/Netherlands/WC2014
... '''
>>> re.findall(r'/team/.*?/Euro_2012', sample)
['/team/Croatia/Euro_2012', '/team/Netherlands/Euro_2012']
>>> re.findall(r'/team/[\w\d%.~+-/]*?/Euro_2012', sample)
['/team/Croatia/Euro_2012', '/team/Netherlands/Euro_2012']