|
|
| Problems? Is your data what you think it is? | |
| PerlMonks |
Elegant (i.e. declarative) way to find all possibly overlapping matchesby jsegal (Friar) |
| on Sep 18, 2003 at 13:45 UTC ( [id://292470]=perlquestion: print w/replies, xml ) | Need Help?? |
This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.jsegal has asked for the wisdom of the Perl Monks concerning the following question:
Howdy. The "canonical" way to find all matches in a string is with m//g. For example, to find the starting positions of a substring "abc" in a string you could do: Now suppose the pattern we are looking for overlaps with itself -- e.g. is aa. The following: does not quite work: if the input string is "baaaad", for example, it would output: It leaves out "found aa at 2", which is entirely expected given how /g is defined (the next match starts after the end of the previous one). Now, it is straightforward enough to tweak the loop so it finds all the matches, using pos as an lvalue: This "tricks" the RE engine to start searching again at the very next character, so all matches will be found, even if they overlap. This works fine, and solves the particular practical problem I am working on, but it got me to thinking: is it possible to get this bevahior purely declaratively -- i.e. in the RE itself, not by tweaking pos after the match? Thanks! Update:Just as I was about to post this, I figured out my own answer, using a lookahead: /(?=aa)./. The lookahead matches without advancing pos, the "." advances pos by 1. Are there other ways to do this? More efficient ways?
Back to
Seekers of Perl Wisdom
|
|
||||||||||||||||||||||||||||||||||||