Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Comment on

by gods
on Feb 11, 2000 at 00:06 UTC ( #3333=superdoc: print w/replies, xml ) Need Help??
as modified from my Perl5-Porters post
If we're able to look at the specific nodes of a regular expression, then we should be able to create a regex that works from the BACK of a string to the FRONT. What do I mean?
($last_numbers) = $string =~ /(\d+)(?!\D*\d)/;
That regex finds the last occurrence of digits in $string. Now, it's not all that bad, but it could be made a great deal simpler by:
  1. reversing the input string
  2. reversing the nodes of the regex (optimize it, too)
  3. reversing the match
"How in the world is that simpler?" you ask. "Just watch!" I reply.
$last_numbers = scalar reverse( # reverse the match reverse($string) =~ # reverse the input string /(\d+)/ # reverse the regex );
Now, the regex (\d+)(?!\D*\d) can also be written as (\d+)(?=\D*$). If digits aren't followed by another digit, then they are followed by only non-digits, if anything. In the process of reversal, the look-ahead can be eliminated, since the regex would be \D*(\d+) which has a redundant leading "node", \D*. The regex's meaning is not changed by its removal.

We already have which can pick a regex apart during compilation and during the actual matching stage. This has the ability to pick apart individual nodes of a regular expression.
Note: the term "node" refers to a combination of regex atoms and quantifiers which can match a given substring backwards or forwards. In the regex \d+[abc]def(foo|bar), the nodes are:
  • \d+
  • [abc]
  • d
  • e
  • f
  • f
  • o *
  • o *
  • b
  • a
  • r
* technically, the two o nodes can be combined here

This regex, reversed, would be (rab|oof)fed[abc]\d+
For the mean time, there is no way to automatically reverse a regex. You have to do it by hand. But the benefits of it are amazing. Maybe they need to be seen to be believed. If so, here is an example.

You have a simple programming language, called KC ("kinda crummy"). It has a VERY simple grammar:
  • comments are matched by <[^>]*>
  • strings are matched by "[^"\\]*(?:\\.[^"\\]*)*"
  • everything else is matched by [^<>"]+
The string definition is a double-quoted strings with escapes allowed in it, like "foo \"bar\" \\ blat". All programs written in KC can be matched by the following regex:
$CODE =~ m{ \A (?: [^<>"]+ # non-string, non-comment | "[^"\\]*(?:\\.[^"\\]*)*" # string | <[^>]*> # comment )* \z }x;
We can write a regex to match an entire file (shown above). Oh, before I go any further, here's the sample program:
<this is a sample program> int x = 10; <what a silly grammar> str y = "cool \" beans"; if (len(y) GREATER_THAN x) { <can't use gt and lt symbols... heehee> <empty comment coming up ! print y, " is longer than ", x, " characters"; <> <and more stuff to come soon> chop(y,x); print "I sliced 'y' down to ", x, " characters for you"; }
Let's say we wanted to extract the LAST comment from this program as well as be sure it was coded properly. Here's my regex. Note: I used the "cut" regex operator (?>...) which matches without allowing a backtrack, to speed up the non-string, non-comment part.
($last_comment) = $CODE =~ m{ \A (?: <[^>]*> | "[^"\\]*(?:\\.[^"\\]*)*" | (?>[^"<>]*) )* (<[^>]*>) (?: "[^"\\]*(?:\\.[^"\\]*)*" | (?>[^"<>]*) )* \z }x;
I'll also implement a reversed version. The reversed terms for the grammar are:
  • comments are matched by >[^>]*<
  • strings are matched by "(?:[^"\\]*.\\)*[^"\\]*"
  • everything else is matched by [^<>"]+
$last = scalar reverse(reverse($CODE) =~ m{ \A (?: "(?:[^"\\]*.\\)*[^"\\]*" | (?>[^"<>]*) )* (>[^>]*<) (?: "(?:[^"\\]*.\\)*[^"\\]*" | (?>[^"<>]*) | >[^>]*< )* \z }x);
If you look long enough (it shouldn't take too long) you'll see that EACH node of the terms has been reversed properly. Now, I ran a benchmark (available on my web site -- follow the links for "Sex, Eger!") and it showed that the reverse method was actually faster than the forward version, EVEN with having to reverse the input string AND the value of $1. When I implemented a cached version, where the reverse of $CODE was already stored, it was even faster (obviously). Here are the wonderful results:

Running for at least 15 seconds
Method Hz # iters

This is, to say the least, very good. The backwards version runs %33 faster, and the cached version runs %50 faster!

If we already know the KC code is well-formed (that is, it will match the entire-code regex), then we can eliminate a lot of the code in the regexes. First, to match the last comment, forwards:
($last_comment) = $CODE =~ m{ (<[^>]*>) (?: "[^"\\]*(?:\\.[^"\\]*)*" | (?>[^"<>]*) )* \z }x;
And now backwards:
$last = scalar reverse(reverse($CODE) =~ m{ \A (?: "(?:[^"\\]*.\\)*[^"\\]*" | (?>[^"<>]*) )* (>[^>]*<) }x);
The benchmark gave me the following data:

Running for at least 15 seconds
Method Hz # iters

Another tremendous difference. The backwards version is %100 faster, and the cached version is %150 faster!

What does this mean? Perhaps you should look into rethinking how you match your strings. If you're looking for the last of something, or for something towards the end of a string, and the string is potentially large, thinking about regex reversal. It could save you a lot of time.

This text will be updated and modified at my web site. I'll put headings in, and all that fancy stuff. :)

Jeff "japhy" Pinyan

In reply to sexeger by japhy

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

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

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

    How do I use this? | Other CB clients
    Other Users?
    Others studying the Monastery: (5)
    As of 2016-09-29 05:29 GMT
    Find Nodes?
      Voting Booth?
      Extraterrestrials haven't visited the Earth yet because:

      Results (547 votes). Check out past polls.