使用正则表达式查找以/ team /开头并以/ Euro_2012结尾的字符串

时间:2014-05-23 20:13:55

标签: python regex

嗨简单问题......

我想找到与以下模式基本匹配的所有字符串:

/team/*/Euro_2012

所以它应该找到:

/team/Croatia/Euro_2012
/team/Netherlands/Euro_2012

但不是:

/team/Netherlands/WC2014

如何使用re.compile在Regex for Python中编写此代码?

1 个答案:

答案 0 :(得分:2)

足够简单:

re.findall(r'/team/.*?/Euro_2012', inputtext)

可能希望限制/team//Euro_2012之间的允许字符,以减少较大文本中误报的可能性:

re.findall(r'/team/[\w\d%.~+-/]*?/Euro_2012', inputtext)

仅允许valid URI characters

演示:

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