Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep or the like: overlapping matches

Tags:

regex

grep

For:

echo "the quick brown fox" | grep -Po '[a-z]+ [a-z]+'

I get:

the quick
brown fox

but I wanted:

the quick
quick brown
brown fox

How?

like image 384
Adrian May Avatar asked Sep 18 '25 16:09

Adrian May


1 Answers

with awk:

 awk '{for(i=1;i<NF;i++) print $i,$(i+1)}' <<<"the quick brown fox"

update: with python:

#!/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)

output:

['the quick', 'quick brown', 'brown fox']
the quick
quick brown
brown fox
like image 65
tso Avatar answered Sep 20 '25 08:09

tso