Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all possible starting positions of a regular expression match in perl, including overlapping matches?

Tags:

perl

Is there a way to find all possible start positions for a regex match in perl?

For example, if your regex was "aa" and the text was "aaaa", it would return 0, 1, and 2, instead of, say 0 and 2.

Obviously, you could just do something like return the first match, and then delete all characters up to and including that starting character, and perform another search, but I'm hoping for something more efficient.

like image 872
jonderry Avatar asked Jan 21 '23 18:01

jonderry


1 Answers

Use lookahead:

$ perl -le 'print $-[0] while "aaaa" =~ /a(?=a)/g'

In general, put everything except the first character of the regex inside of the (?=...).

like image 79
Sean Avatar answered Jan 31 '23 00:01

Sean