Python正则表达式,在字符串中多次出现1 +连续字符串

时间:2017-07-18 13:42:20

标签: python regex string

我需要找到可变长度字符序列的起始和结束位置,由字符串内的相同1个字母组成。 我看到了这个话题Finding multiple occurrences of a string within a string in Python,但我认为它有点偏离。

以下什么都没有给我,而我希望找到5个元素。

import re
s = 'aaaaabaaaabaaabaaba'
pattern = '(a)\1+'
for el in re.finditer(pattern, s):
    print 'str found', el.start(), el.end()

提前致谢。

1 个答案:

答案 0 :(得分:-1)

由于它是一个正则表达式,反斜杠应在字符串级别进行转义,但应由正则表达式解释。

您可以使用原始字符串:

import re
s = 'aaaaabaaaabaaabaaba'
pattern = r'(a)\1+'   # raw string
for el in re.finditer(pattern, s):
    print 'str found', el.start(), el.end()

这会产生:

str found 0 5
str found 6 10
str found 11 14
str found 15 17