Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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:
while ($s =~ /abc/g) { print "found abc at $-[0]\n"; }
Now suppose the pattern we are looking for overlaps with itself -- e.g. is aa. The following:
while ($s =~ /aa/g) { print "found aa at $-[0]\n"; }
does not quite work: if the input string is "baaaad", for example, it would output:
found aa at 1 found aa at 3
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:

while ($s =~ /aa/g) { print "found aa at $-[0]\n"; pos($s) = $-[0] + 1; }
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?

--JAS


In reply to Elegant (i.e. declarative) way to find all possibly overlapping matches by jsegal

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2024-04-19 12:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found