echo "the quick brown fox" | grep -Po '[a-z]+ [a-z]+'
我得到:
the quick
brown fox
,但我想:
the quick
quick brown
brown fox
如何?
echo "the quick brown fox" | grep -Po '[a-z]+ [a-z]+'
我得到:
the quick
brown fox
,但我想:
the quick
quick brown
brown fox
如何?
與awk
:
awk '{for(i=1;i<NF;i++) print $i,$(i+1)}' <<<"the quick brown fox"
更新: 用蟒:
#!/usr/bin/python3.5
import re
s="the quick brown fox"
matches = re.finditer(r'(?=(\b[a-z]+\b \b[a-z]+\b))',s)
ans=[i.group(1) for i in matches]
print(ans) #or not print
for i in ans:
print(i)
輸出:
['the quick', 'quick brown', 'brown fox']
the quick
quick brown
brown fox
這個問題的目的是更廣泛的意義。我想我沒有真正說清楚。一般來說,我想以這樣的方式運行正則表達式,以便返回所有可能的匹配。我看到的行爲即使是有效的匹配,也不會返回「快速棕色」。 –
我有更新答案。 – tso
另一個AWK:
awk '{print $1,$2 RS $2,$3 RS $3,$4}' <<<"the quick brown fox"
the quick
quick brown
brown fox
我以上30秒前的評論也適用於此。 –
我不是專家,但我不認爲你可以用grep來做到這一點。你應該嘗試編寫一個perl或awk腳本。 – gmoshkin
使用Perl,您可以輕鬆完成,而不是使用grep,因爲grep不允許訪問捕獲組內容。 –
如果你使用某些你可以打印的組,那麼重疊模式是'([a-z] +)(?=([a-z] +))''在哪裏打印$ 1 $ 2' – sln