Skip to content

ronsavage/Regexp-Assemble

Repository files navigation

This file is the README for Regexp::Assemble version 0.35

INSTALLATION

perl Makefile.PL
make
make test
make install

TESTING

This module requires the following modules for thorough testing:

  Test::More
  Test::File::Contents
  Test::Pod
  Test::Pod::Coverage
  Test::Warn

The test suite will make allowances for their eventual absence.

It can also make use of Devel::Cover if available.

UNINSTALLATION

This is a pure-Perl module. The following one-liner should print
out the canonical path of the file:

  perl -MRegexp::Assemble -le 'print $INC{"Regexp/Assemble.pm"}'

Just delete this file. There is also the question of the man page.
Finding that is left as an exercise to the reader.

BASIC USAGE

use Regexp::Assemble;

my $ra = Regexp::Assemble->new;
$ra->add( 'ab+c' );
$ra->add( 'ab+\\d*\\s+c' );
$ra->add( 'a\\w+\\d+' );
$ra->add( 'a\\d+' );
print $ra->re; # prints (?:a(?:b+(?:\d*\s+)?c|(?:\w+)?\d+))

or

my $ra = Regexp::Assemble->new
	->add( 'foo', 'bar', 'baz', 'foom' );

print "$_ matches\n" if /$ra/
	for (qw/word more stuff food rabble bark/);

or

use Regexp::Assemble;
my @word = qw/flip flop slip slop/;

print Regexp::Assemble->new->add(@word)->as_string;
	# produces [fs]l[io]p

print Regexp::Assemble->new->add(@word)->reduce(0)->as_string;
	# produces (?:fl(?:ip|op)|sl(?:ip|op))

See the ./eg directory for some example scripts.

ADVANCED USAGE

If you want to match things with exceptions, you can use a two
stage process to build a pattern with negative lookbehind. Consider
the following script:

== example begin ==
use Regexp::Assemble;

my $set = [
	{
		accept => [qw[ .cnn.net .cnn.com ]],
		refuse => [qw[ ^media video ]],
	},
	{
		accept => [qw[ .yahoo.com ]],
	},
];

my $ra = Regexp::Assemble->new;

for my $s( @$set ) {
	my $refuse = do {
		if( not exists $s->{refuse} ) {
			'';
		}
		else {
			'(?<!'
			. Regexp::Assemble->new->add( @{$s->{refuse}} )->as_string
			. ')'
		}
	};
	$ra->add( map { s/\./\\./g; "$refuse$_\$" } @{$s->{accept}} );
}

my $re = $ra->re;

print $ra->as_string, "\n";

while( <> ) {
	print;
	chomp;
	print "\t", (/$re/ ? 'yep' : 'nope'), "\n";
}

== example end ==

and a datafile to run it on:

== data begin ==
media.cnn.com
more.video.cnn.net
super.media.cnn.com
video.cnn.net
video.yahoo.com
www.cnn.com
www.cnn.net
www.yahoo.com
== data end ==

This lets us match arbitrary hosts within a domain, but at the same
time excluding a subset of hosts that we wish to ignore.

TRACKING REGULAR EXPRESSION MATCHES

Regexp::Assemble can emit regular expressions that, when used correctly,
can let you determine which original pattern gave rise to the match.
This technique is known as tracking.

== example begin ==

use strict;
use Regexp::Assemble;

my $dispatch = {
	'a-(\\d+)'        => sub { my $v = shift; print "speed $v->[1]\n"; },
	'a-(\\d+)-(\\d+)' => sub { my $v = shift; print "pressure $v->[1] over $v->[2]\n"; },
	'a-(\\w+)-(\\w+)' => sub { my $v = shift; print "message $v->[1] from $v->[2]\n"; },
};

my $re = Regexp::Assemble->new( track => 1 )->add( keys %$dispatch );

while( <> ) {
	chomp;
	if( $re->match($_) ) {
		$dispatch->{ $re->matched }( $re->mvar() );
	}
	else {
		last if /q/;
		print "\tignored\n";
	}
}

== example end ==

Run this and enter lines like a-234, a-654, a-345-345, a-dog-cat and so
on. When the pattern matches a string, you can retrieve the pattern
that caused the match to occur, and dispatch it to a routine that knows
what to do about it. You can retrieve captured values too. In the above
example, just remember that $v->[1] eq $1. $v->[0], a.k.a $re->mvar(0)
happens to be the the same as the input parameter to match (although
this is worked out from first principles, more or less, not simply by
copying the parameter).

I initially hoped that $^R would handle this sort of stuff for me, but
there's a bug. Consider the following pattern:

	a(?{1}) (?: b(?{2}) )?

(whitespace added for clarity). This pattern will match both the strings
'a' and 'ab', however, in both cases, $^R will be set to 1 aftewards. I
would have hoped that after matching 'ab', that $^R would be set to 2.

As of perl 5.9.5, this bug has been corrected in the regular expression
engine, thanks to Yves Orton. Version 0.29 takes this into account, and
as a result re 'eval' is no longer required in Perl 5.10.

IMPLEMENTATION

Consider a simple pattern 'costructive' we want to use to match against
strings. This pattern is split into tokens, and is stored in a list:

  [c o n s t r u c t i v e]

At this point, if we want to produce a regular expression, we only need
to join it up again:

   my $pattern = join( '' => @path);
   my $re = qr/$pattern/;

Consider a second pattern 'containment'. Split into a list gives:

  [c o n t a i n m e n t]

We then have to merge this second path into the first path. At some
point, the paths diverge. The first element path the point of
divergence in the first path is replace by a node (a hash) and the two
different paths carry on from there:

  [c o n
		|s => [s t r u c t i v e]
		\t => [t a i n m e n t]
  ]

And then 'confinement':

  [c o n
		|s => [s t r u c t i v e]
		|t => [t a i n m e n t]
		\f => [f i n e m e n t]
  ]

What happens if we add a path that runs out in the middle of a
previous path?  We add a node, and a "null-path" to indicate that
the path can both continue on, and can also stop here:

Add 'construct':

  [c o n
		|s => [s t r u c t
		|                 | '' => undef
		|                 \ i => [i v e]
		|     ]
		|t => [t a i n m e n t]
		\f => [f i n e m e n t]
  ]

It should be obvious to see how the contruct branch will produce the
pattern /construct(?:ive)?/ . Or for a longer path 'constructively':

  [c o n
		|s => [s t r u c t
		|                 | '' => undef
		|                 \ i => [i v e
		|                              | '' => undef
		|                              \ l => [l y]
		|                        ]
		|     ]
		|t => [t a i n m e n t]
		\f => [f i n e m e n t]
  ]

This is the state of the internal structure before reduction. When
traversed it will produce a valid regular expression.

The trick is how to perform the reduction. The key insight is to note
that for any part of the trunk where the sibling paths do not end in
a node, it it possible to reverse them, and insert them into their
own R::A object and see what comes out:

  [t a i n m e n t] =>
  [t n e m n i a t]

  [f i n e m e n t] =>
  [t n e m e n i f]

Gives:

  [t n e m
		  | n => [n i a t]
		  \ e => [e n i f]
  ]

When the algorithm visits the other path (s => [s t r u c t ...]),
it behaves differently. When a null path is seen, no reduction is
performed at that node level. The resulting path would otherwise
begin to admit matches that are are not permitted by any of the
initial patterns. For instance, with bat, cat, and catty, you can
hardly try to merge 'bat' and 'cat' to produce [bc]at, otherwise the
resulting pattern would become [bc]at(ty)?, and that would incorrectly
match 'batty'.

After having visited the s, t, and f paths, the
result is that t and f were reduced, and s failed. We therefore
unreverse everything, and signal that this node cannot participate in
any more reduction (the failures percolate up the tree back to the
root).

Unreversing the t, f reduction gives:

  [ t => [t a i n] \
	f => [f i n e] | m e n t ]

When all is said and done, the final result gives

  [c o n
		|s => [s t r u c t
		|                 | '' => undef
		|                 \ i => [i v e
		|                              | '' => undef
		|                              \ l => [l y]
		|                        ]
		|     ]
		[ t => [t a i n]
		  f => [f i n e] m e n t ]
  ]

When this data structure is traversed to build the pattern, it gives

  con(struct(ive(ly)?)?|(fine|tain)ment)

NB: The capturing syntax is used here, instead of the grouping
syntax for readability issues only.

On the other hand, if the s path contained only [s t r u c t], then
the reduction would have gone succeeded. We would have a common
head [t], shared by all three paths.

  [t
	| c => [c u r t s]
	\ n => [n e m
				 | n => [n i a t]
				 \ e => [e n i f]
		   ]
  ]

And then consider that the path [c o u r t] had also been added to
the object. We would then be able to reduce the t from the above
reduction, and the t in [c o u r t]

  [c o
	  | n => [n
	  |        | s => [s t r u c t]
	  |        | t => [t a i n m e n t]
	  |        \ f => [f i n e m e n t]
	  |      ]
	  \ u => [u r t]
  ]

gives

  [c o
	  | n => [n
	  |        | s => [s t r u c]
	  |        \ f => [
	  |                 f => [f i n e]
	  |                 t => [t a i n]
	  |                 m e n
	  |               ]
	  |      ]
	  \ u => [u r]
   t
  ]

(Here ends my ASCII art talents).

The above structure would give

  co(n(struc|(fine|tai)men)|ur)t

In a nutshell, that's it. Seems like the code would be simple, huh?
It turns out that no, there are lots of fiddly edge cases,
especially sets of paths are the same as other sets of paths
except for an optional sub-path. The canonical example that the
test suite deals with is:

  showeriness, showerless, showiness, showless.

The final pattern is

  show(er)?(in|l)ess

If there are bugs to be found, it will be in cases that are even
more pathological than this, e.g., something like:

  show(er)?(i(a|po)?n|l)ess

(although the above actually *does* work, I tried it)

TESTING STRATEGY USED

The code has been heavily tested using an approach based on
combinatoric lists known as power sets. For instance, the power
set of (a,b,c,d) is (assuming a join() on the results):

 a ab abc abcd abd ac acd ad b bc bcd bd c cd d

(along with the empty set). The power set of N elements contains
2**N elements. (or 2**N-1 of we exclude the empty set).

The testing approach was then to take the power set of the above
power set and produce regular expressions from each element.

For instance, at some point, we would encounter the set

  abc ac bcd cd d

From this we generate the pattern (?:(?:b?c)?d|ab?c). Once we have
this pattern, we go back and check that it does in fact match the
above 5 elements, and furthermore, that it does *not match* the
remaining 10 elements of the power set not used in this iteration.

And yes, that shook out a couple of bugs.

As of this time, the following search space has been examined

a b c         - complete
a b c d       - complete
a b c d e     - runs of 1-11, 20-31 complete, 12-17 partial
a b c d e f   - runs of 1-5, 61-63 complete
a b c d e f g - runs of 1-4, 125-127 complete

The code for this is in the eg/stress-test script. Note: it can use
months of CPU time if you're not careful. It requires the following
modules:

  Algorithm::Combinatorics
  Data::PowerSet

OTHER CONSIDERATIONS

When tracking is in use, no reduction is performed.

Pretty-printed (indented), and tracking is handled merely by calling
different output routines. Each routine emits things in a different
way, but the underlying structure remains the same. Which is one
reason why you can't have pretty-printed tracked patterns (Well you
can, but I haven't written the routine that would do so).

Zero-width lookahead assertions can be added to the pattern. This may
be a win, but it may also slow things down.

DEBUGGING NOTES

If you are curious, you can dump out the internal data struct with
the following:

  use Data::Dumper;
  $Data::Dumper::Terse     = 0;
  $Data::Dumper::Indent    = 0;
  $Data::Dumper::Quotekeys = 0;
  $Data::Dumper::Pair      = '=>';

  print Dumper($r->_path);

A more compact representation can be obtained with

  print $r->dump;

All that said, I'm now reasonably confident that it deals
correctly with pretty much anything you're likely to throw at it.

Two recent bugs were easy to spot in the code, and the fix was a
couple of lines. Adding lookahead assertion was pretty simple to,
even if it did result in a certain amount of code factoring. So I
think that in general the structure of the code is a good one.

The eg/debugging script offers a good strategy for dealing with
assemblies that give rise to uncompilable patterns.

STATUS

This module is under active development. The module is managed in
a Subversion repository, and thus, the latest working copy is
available at

  https://github.com/ronsavage/Regexp-Assemble

AUTHOR

David Landgren

Ron Savage is co-maint of the module, starting with V 0.36.

I do appreciate getting e-mail, especially about Perl. Please keep in
mind that I get a lot of spam, and take drastic measures to reduce the
flow. One of the measures involves a gigantic regular expression that
contains many thousands of patterns that match hostnames of dynamic
dialup/residential/home IP addresses. That pattern is of course built
with this module.

It would be ironic if I rejected your mail coming from such an address.
Please use your ISP's outbound MX, or pay what it takes to get your
reverse DNS changed to something else.

COPYRIGHT

This module is copyright (C) David Landgren 2004-2008.
All rights reserved.

LICENSE

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

About

Assemble multiple Regular Expressions into a single RE

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published