我試圖找到字符串中的一組字符的所有組合,但發現的字符集必須具有特定的長度。我曾想過使用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