Python:使用必须在花括号{}

时间:2015-05-15 14:02:47

标签: python regex

我的任务是使用正则表达式创建一个函数,该函数返回长度为count个字符的匹配项。

这是我试过的:

import re

# EXAMPLE:
# >>> find_words(4, "dog, cat, baby, balloon, me")
# ['baby', 'balloon']

def find_words(count, a_string):
    pattern = r'\w{{{},}}'.format(count)
    return re.findall(pattern, a_string)

大括号乱七八糟的原因是我试图escape them

我想要的最终搜索字符串(pattern)类似于\w{ count ,}

编辑:忘记原帖中的return语句。我会留在这里,因为进来的答案实际上是有价值的。

1 个答案:

答案 0 :(得分:3)

为什么不使用%运营商?

In [1]: def find_words(count, a_string):
   ...:     pattern = r'\w{%s,}' % count
   ...:     return re.findall(pattern, a_string)

In [2]: find_words(4, "dog, cat, baby, balloon, me")
Out[2]: ['baby', 'balloon']