我试图找到字符串中一组字符的所有组合,但是找到的字符集必须具有特定的长度。我曾经想过使用set function []和出现次数函数{:},我似乎无法让它们一起工作。
该示例应该返回'这个'和'点击'
谢谢。
def test_patterns(text, patterns=[]):
"""Given source text and a list of patterns, look for
matches for each pattern within the text and print
them to stdout.
"""
# Look for each pattern in the text and print the results
for pattern, desc in patterns:
print "Pattern %r (%s)\n" % (pattern, desc)
print ' %r' % text
for match in re.finditer(pattern, text):
s = match.start()
e = match.end()
#substr = match.group()
substr = text[s:e]
n_backslashes = text[:s].count('\\')
prefix = '.' * (s + n_backslashes)
print ' %s%r' % (prefix, substr)
print
return
if __name__ == '__main__':
test_patterns('Does this text contain hits or matches?', [('[this]{4:4}+', "Description"),])
raw_input()
答案 0 :(得分:1)
quatifier {m}
要求以下正则表达式m
次
例如
>>> st="Does this text contain hits or matches"
>>> re.findall(r'[this]{4}', st)
['this', 'hits']
或者更具体
>>> re.findall(r'\b[this]{4}\b', st)
['this', 'hits']
与写作相同
>>> re.findall(r'\b[this]{4,4}\b', st)
['this', 'hits']