Python正则表达式:是否有一个符号来搜索模式的多个出现?

时间:2015-09-21 08:57:19

标签: python regex

我知道*为0或更多,+为1或更多,但如果我想表示2个或更多(超过1)怎么办?

例如,我有

>>> y = 'U0_0, P33, AVG'
>>> re.findall(r'[a-zA-Z]+', y)
['U', 'P', 'AVG']

但我只想获得有2个或更多字母的那些。在此示例中,AVG

我该怎么做?

2 个答案:

答案 0 :(得分:3)

您可以使用以下代替*+

{2,}     (two or more)

此外,如果你想匹配2到5,你可以这样做:

{2,5}    (two to five example)

答案 1 :(得分:3)

y = 'U0_0, P33, AVG'
print re.findall(r'[a-zA-Z]{2,}', y)

                            ^^^  

{m,n} Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 'a' characters. Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an example, a{4,}b will match aaaab or a thousand 'a' characters followed by a b, but not aaab. The comma may not be omitted or the modifier would be confused with the previously described form.