in reply to Re: Optimizing regular expressions
in thread Optimizing regular expressions

I appreciate the help, and I'm sorry for such a general question. One thing to make clear is that the ignore_first and ignore_last characters are subsets of wordchars. The point of those settings is to allow characters within a word, but not at the start/end. The classic example is that a dot is ok within a host name, but not at the end (e.g. at the end of a sentence).

The other thing that complicates this a bit is I'm not showing all the original text with the words highlighted in the final output, but rather just a few words on either side of the highlighted text. Like a google search shows. Thus, I also need to be careful not to print words twice when highlighted words are close together.

That is the reason I split the source text into an array of "swish" words and non swish words -- so I could easily mark words on either side of the matched word.

@words = split /([^$wordchars])/, $source_text;<p>

I use two arrays to track this now (instead of an array of arrays) as it was faster to avoid all the dereferencing.

Here's a specific question: The "problem" with the above code is that I still need to remove the leading and trailing ignore characters. So, that's an extra pattern match for every word - one time for the split, and then another to extract out a word from its ignore chars.

I tried to find an expression to use in the above spilt that would do this in one shot, but it was looking like a complicated expression that might be slower than doing two matches. But I never found a pattern that I could test.

I also wonder if using a repeating pattern with /g might be faster than my word-by-word checking. But then I'm back to the problem of how to print the words around the match.

Thanks again for your help.

Replies are listed 'Best First'.
Re: Re: Re: Optimizing regular expressions
by japhy (Canon) on Jun 02, 2001 at 18:41 UTC
    I wrote up a module you might find useful. Let me know if it, or the test program, needs some documentation. It appears to be quite nifty. Swish.pm

    japhy -- Perl and Regex Hacker
      Interesting. Needed a few tweaks to compile (maybe I grabbed an early version).

      It also drops the non-wordchars in output, and I couldn't get the context to work when matches were closer than BEFORE and AFTER settings.

      I'll spend some time with your code later, as it's an interesting approach. I like your coding style, too!

      Anyway, you can see that this not a trivial problem to solve... I'll keep checking back.

      Thanks again,

      BTW -- did you try running the code I posted?

        I was forgetting some capturing parentheses. I've gotten it fixed now, and it seems to run fine. I've not yet run your code, because after I saw your post, I was very interested in finding out how to do stream matching, so I wanted to write my own.

        japhy -- Perl and Regex Hacker