2017-07-18 18 views
0

我需要查找字符串中包含相同1個字母的可變長度字符序列的開始和結束位置。 我看到這個主題Finding multiple occurrences of a string within a string in Python,但我認爲它有點關閉。在一個字符串中多次出現1個連續字符串的Python正則表達式

以下給我什麼,而我期望找到5個元素。

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

在此先感謝。

+0

[它運作良好,只是用**原始字符串字面**](https://開頭ideone。 COM/SxWJdh)。你只能期待4個結果。否則,用'*'替換'+'。 –

+0

WiktorStribiżew,謝謝,尤其是關於*的小費。 – psb

回答

-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 
+0

非常感謝。標記爲已接受。 – psb

相關問題