2017-02-26 53 views
1

長度爲2的所有字符串我想提取文本的所有兩字母串用正則表達式,例如:提取與Re.Findall

just a test 

會得到我ju, us, st, te, es, st

我嘗試使用:re.findall(r'\w{2}',text),但它只分爲2個字母的字符串,並給我ju, st, te, st

非常感謝您的幫助。

+1

使用['re.findall(r'(?=(\ w {2}))',text)'](http://ideone.com/XucVPm)。 –

+0

沒有正則表達式:'print([「」。join(x)for w in「just a test」.split()if len(w)> 1 for zip in(w,w [1:])]))' –

+0

@sin:他標記爲重複,然後評論(未回答)以幫助OP在他的具體問題。我只是希望我可以發佈我的非正則表達式解決方案。 –

回答

2

我將離開正則表達式的解決方案,正則表達式的專家(這我不是),因爲它可以在沒有正則表達式很簡單,在一個班輪列表解析完成:

s = "just a test" 
result = ["".join(x) for w in s.split() if len(w)>1 for x in zip(w,w[1:])] 

print(result) 

結果:

['ju', 'us', 'st', 'te', 'es', 'st'] 

剛剛拆分的話,用了不到2個字符過濾掉的話,並使用zip

只能如果T交錯他們對他們的移動副本當然這裏沒有標點符號。