我试图找到字符串中的一组字符的所有组合,但发现的字符集必须具有特定的长度。我曾想过使用set函数[]和函数{:}的出现次数,我似乎无法让它们一起工作。Python正则表达式:设置前缀长度的组合
示例应该返回'this'和'hit'
谢谢。
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()
好吧,我不知道。 – grasshopper 2014-11-21 11:13:35
例子?你是指这个:“这个文本是否包含命中或匹配?” – grasshopper 2014-11-21 11:14:53
@Kasra从下面的答案,似乎他们一起工作。 – grasshopper 2014-11-21 11:19:09