File: README

package info (click to toggle)
libregexp-assemble-perl 0.36-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 580 kB
  • ctags: 101
  • sloc: perl: 2,272; makefile: 8
file content (487 lines) | stat: -rw-r--r-- 13,506 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
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

  http://svnweb.mongueurs.net/Regexp-Assemble/trunk

AUTHOR

David Landgren

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.