]> git.vpit.fr Git - perl/modules/Regexp-Wildcards.git/blob - lib/Regexp/Wildcards.pm
More linefeeds make the POD clearer
[perl/modules/Regexp-Wildcards.git] / lib / Regexp / Wildcards.pm
1 package Regexp::Wildcards;
2
3 use strict;
4 use warnings;
5
6 use Carp qw/croak/;
7 use Text::Balanced qw/extract_bracketed/;
8
9 =head1 NAME
10
11 Regexp::Wildcards - Converts wildcard expressions to Perl regular expressions.
12
13 =head1 VERSION
14
15 Version 1.02
16
17 =cut
18
19 use vars qw/$VERSION/;
20 BEGIN {
21  $VERSION = '1.02';
22 }
23
24 =head1 SYNOPSIS
25
26     use Regexp::Wildcards;
27
28     my $rw = Regexp::Wildcards->new(type => 'unix');
29
30     my $re;
31     $re = $rw->convert('a{b?,c}*');          # Do it Unix shell style.
32     $re = $rw->convert('a?,b*',   'win32');  # Do it Windows shell style.
33     $re = $rw->convert('*{x,y}?', 'jokers'); # Process the jokers and escape the rest.
34     $re = $rw->convert('%a_c%',   'sql');    # Turn SQL wildcards into regexps.
35
36     $rw = Regexp::Wildcards->new(
37      do      => [ qw/jokers brackets/ ], # Do jokers and brackets.
38      capture => [ qw/any greedy/ ],      # Capture *'s greedily.
39     );
40
41     $rw->do(add => 'groups');            # Don't escape groups.
42     $rw->capture(rem => [ qw/greedy/ ]); # Actually we want non-greedy matches.
43     $re = $rw->convert('*a{,(b)?}?c*');  # '(.*?)a(?:|(b).).c(.*?)'
44     $rw->capture();                      # No more captures.
45
46 =head1 DESCRIPTION
47
48 In many situations, users may want to specify patterns to match but don't need the full power of regexps.
49 Wildcards make one of those sets of simplified rules.
50 This module converts wildcard expressions to Perl regular expressions, so that you can use them for matching.
51
52 It handles the C<*> and C<?> jokers, as well as Unix bracketed alternatives C<{,}>, but also C<%> and C<_> SQL wildcards.
53 If required, it can also keep original C<(...)> groups or C<^> and C<$> anchors.
54 Backspace (C<\>) is used as an escape character.
55
56 Typesets that mimic the behaviour of Windows and Unix shells are also provided.
57
58 =head1 METHODS
59
60 =cut
61
62 sub _check_self {
63  croak 'First argument isn\'t a valid ' . __PACKAGE__ . ' object'
64   unless ref $_[0] and $_[0]->isa(__PACKAGE__);
65 }
66
67 my %types = (
68  jokers   => [ qw/jokers/ ],
69  sql      => [ qw/sql/ ],
70  commas   => [ qw/commas/ ],
71  brackets => [ qw/brackets/ ],
72  unix     => [ qw/jokers brackets/ ],
73  win32    => [ qw/jokers commas/ ],
74 );
75 $types{$_} = $types{win32} for qw/dos os2 MSWin32 cygwin/;
76 $types{$_} = $types{unix}  for qw/linux
77                                   darwin machten next
78                                   aix irix hpux dgux dynixptx
79                                   bsdos freebsd openbsd
80                                   svr4 solaris sunos dec_osf
81                                   sco_sv unicos unicosmk/;
82
83 my %escapes = (
84  jokers   => '?*',
85  sql      => '_%',
86  commas   => ',',
87  brackets => '{},',
88  groups   => '()',
89  anchors  => '^$',
90 );
91
92 my %captures = (
93  single   => sub { $_[1] ? '(.)' : '.' },
94  any      => sub { $_[1] ? ($_[0]->{greedy} ? '(.*)'
95                                             : '(.*?)')
96                          : '.*' },
97  brackets => sub { $_[1] ? '(' : '(?:'; },
98  greedy   => undef
99 );
100
101 sub _validate {
102  my $self  = shift;
103  _check_self $self;
104  my $valid = shift;
105  my $old   = shift;
106  $old = { } unless defined $old;
107  my $c;
108  if (@_ <= 1) {
109   $c = { set => $_[0] };
110  } elsif (@_ % 2) {
111   croak 'Arguments must be passed as an unique scalar or as key => value pairs';
112  } else {
113   my %args = @_;
114   $c = { map { (exists $args{$_}) ? ($_ => $args{$_}) : () } qw/set add rem/ };
115  }
116  for (qw/set add rem/) {
117   my $v = $c->{$_};
118   next unless defined $v;
119   my $cb = {
120    ''      => sub { +{ ($_[0] => 1) x (exists $valid->{$_[0]}) } },
121    'ARRAY' => sub { +{ map { ($_ => 1) x (exists $valid->{$_}) } @{$_[0]} } },
122    'HASH'  => sub { +{ map { ($_ => $_[0]->{$_}) x (exists $valid->{$_}) }
123                         keys %{$_[0]} } }
124   }->{ ref $v };
125   croak 'Wrong option set' unless $cb;
126   $c->{$_} = $cb->($v);
127  }
128  my $config = (exists $c->{set}) ? $c->{set} : $old;
129  $config->{$_} = $c->{add}->{$_} for grep $c->{add}->{$_},
130                                                 keys %{$c->{add} || {}};
131  delete $config->{$_} for grep $c->{rem}->{$_}, keys %{$c->{rem} || {}};
132  $config;
133 }
134
135 sub _do {
136  my $self = shift;
137  my $config;
138  $config->{do} = $self->_validate(\%escapes, $self->{do}, @_);
139  $config->{escape} = '';
140  $config->{escape} .= $escapes{$_} for keys %{$config->{do}};
141  $config->{escape} = quotemeta $config->{escape};
142  $config;
143 }
144
145 sub do {
146  my $self = shift;
147  _check_self $self;
148  my $config = $self->_do(@_);
149  $self->{$_} = $config->{$_} for keys %$config;
150  $self;
151 }
152
153 sub _capture {
154  my $self = shift;
155  my $config;
156  $config->{capture} = $self->_validate(\%captures, $self->{capture}, @_);
157  $config->{greedy}  = delete $config->{capture}->{greedy};
158  for (keys %captures) {
159   $config->{'c_' . $_} = $captures{$_}->($config, $config->{capture}->{$_})
160                                                if $captures{$_}; # Skip 'greedy'
161  }
162  $config;
163 }
164
165 sub capture {
166  my $self = shift;
167  _check_self $self;
168  my $config = $self->_capture(@_);
169  $self->{$_} = $config->{$_} for keys %$config;
170  $self;
171 }
172
173 sub _type {
174  my ($self, $type) = @_;
175  $type = 'unix'      unless defined $type;
176  croak 'Wrong type'  unless exists $types{$type};
177  my $config = $self->_do($types{$type});
178  $config->{type} = $type;
179  $config;
180 }
181
182 sub type {
183  my $self = shift;
184  _check_self $self;
185  my $config = $self->_type(@_);
186  $self->{$_} = $config->{$_} for keys %$config;
187  $self;
188 }
189
190 sub new {
191  my $class = shift;
192  $class = ref($class) || $class || __PACKAGE__;
193  croak 'Optional arguments must be passed as key => value pairs' if @_ % 2;
194  my %args = @_;
195  my $self = { };
196  bless $self, $class;
197  if (defined $args{do}) {
198   $self->do($args{do});
199  } else {
200   $self->type($args{type});
201  }
202  $self->capture($args{capture});
203 }
204
205 =head2 C<< new [ do => $what E<verbar> type => $type ], capture => $captures >>
206
207 Constructs a new L<Regexp::Wildcard> object.
208
209 C<do> lists all features that should be enabled when converting wildcards to regexps.
210 Refer to L</do> for details on what can be passed in C<$what>.
211
212 The C<type> specifies a predefined set of C<do> features to use.
213 See L</type> for details on which types are valid.
214 The C<do> option overrides C<type>.
215
216 C<capture> lists which atoms should be capturing.
217 Refer to L</capture> for more details.
218
219 =head2 C<< do [ $what E<verbar> set => $c1, add => $c2, rem => $c3 ] >>
220
221 Specifies the list of metacharacters to convert or to prevent for escaping.
222 They fit into six classes :
223
224 =over 4
225
226 =item *
227
228 C<'jokers'> converts C<?> to C<.> and C<*> to C<.*> ;
229
230     'a**\\*b??\\?c' ==> 'a.*\\*b..\\?c'
231
232 =item *
233
234 C<'sql'> converts C<_> to C<.> and C<%> to C<.*> ;
235
236     'a%%\\%b__\\_c' ==> 'a.*\\%b..\\_c'
237
238 =item *
239
240 C<'commas'> converts all C<,> to C<|> and puts the complete resulting regular expression inside C<(?: ... )> ;
241
242     'a,b{c,d},e' ==> '(?:a|b\\{c|d\\}|e)'
243
244 =item *
245
246 C<'brackets'> converts all matching C<{ ... ,  ... }> brackets to C<(?: ... | ... )> alternations.
247 If some brackets are unbalanced, it tries to substitute as many of them as possible, and then escape the remaining unmatched C<{> and C<}>.
248 Commas outside of any bracket-delimited block are also escaped ;
249
250     'a,b{c,d},e'    ==> 'a\\,b(?:c|d)\\,e'
251     '{a\\{b,c}d,e}' ==> '(?:a\\{b|c)d\\,e\\}'
252     '{a{b,c\\}d,e}' ==> '\\{a\\{b\\,c\\}d\\,e\\}'
253
254 =item *
255
256 C<'groups'> keeps the parenthesis C<( ... )> of the original string without escaping them.
257 Currently, no check is done to ensure that the parenthesis are matching.
258
259     'a(b(c))d\\(\\)' ==> (no change)
260
261 =item *
262
263 C<'anchors'> prevents the I<beginning-of-line> C<^> and I<end-of-line> C<$> anchors to be escaped.
264 Since C<[...]> character class are currently escaped, a C<^> will always be interpreted as I<beginning-of-line>.
265
266     'a^b$c' ==> (no change)
267
268 =back
269
270 Each C<$c> can be any of :
271
272 =over 4
273
274 =item *
275
276 A hash reference, with wanted metacharacter group names (described above) as keys and booleans as values ;
277
278 =item *
279
280 An array reference containing the list of wanted metacharacter classes ;
281
282 =item *
283
284 A plain scalar, when only one group is required.
285
286 =back
287
288 When C<set> is present, the classes given as its value replace the current object options.
289 Then the C<add> classes are added, and the C<rem> classes removed.
290
291 Passing a sole scalar C<$what> is equivalent as passing C<< set => $what >>.
292 No argument means C<< set => [ ] >>.
293
294     $rw->do(set => 'jokers');           # Only translate jokers.
295     $rw->do('jokers');                  # Same.
296     $rw->do(add => [ qw/sql commas/ ]); # Translate also SQL and commas.
297     $rw->do(rem => 'jokers');           # Specifying both 'sql' and 'jokers' is useless.
298     $rw->do();                          # Translate nothing.
299
300 =head2 C<type $type>
301
302 Notifies to convert the metacharacters that corresponds to the predefined type C<$type>.
303 C<$type> can be any of :
304
305 =over 4
306
307 =item *
308
309 C<'jokers'>, C<'sql'>, C<'commas'>, C<'brackets'>
310
311 Singleton types that enable the corresponding C<do> classes.
312
313 =item *
314
315 C<'unix'>
316
317 Covers typical Unix shell globbing features (effectively C<'jokers'> and C<'brackets'>).
318
319 =item *
320
321 C<$^O> values for common Unix systems
322
323 Wrap to C<'unix'> (see L<perlport> for the list).
324
325 =item *
326
327 C<undef>
328
329 Defaults to C<'unix'>.
330
331 =item *
332
333 C<'win32'>
334
335 Covers typical Windows shell globbing features (effectively C<'jokers'> and C<'commas'>).
336
337 =item *
338
339 C<'dos'>, C<'os2'>, C<'MSWin32'>, C<'cygwin'>
340
341 Wrap to C<'win32'>.
342
343 =back
344
345 In particular, you can usually pass C<$^O> as the C<$type> and get the corresponding shell behaviour.
346
347     $rw->type('win32'); # Set type to win32.
348     $rw->type($^O);     # Set type to unix on Unices and win32 on Windows
349     $rw->type();        # Set type to unix.
350
351 The C<type> method returns the L<Regexp::Wildcards> object.
352
353 =head2 C<< capture [ $captures E<verbar> set => $c1, add => $c2, rem => $c3 ] >>
354
355 Specifies the list of atoms to capture.
356 This method works like L</do>, except that the classes are different :
357
358 =over 4
359
360 =item *
361
362 C<'single'> will capture all unescaped I<"exactly one"> metacharacters, i.e. C<?> for wildcards or C<_> for SQL ;
363
364     'a???b\\??' ==> 'a(.)(.)(.)b\\?(.)'
365     'a___b\\__' ==> 'a(.)(.)(.)b\\_(.)'
366
367 =item *
368
369 C<'any'> will capture all unescaped I<"any"> metacharacters, i.e. C<*> for wildcards or C<%> for SQL ;
370
371     'a***b\\**' ==> 'a(.*)b\\*(.*)'
372     'a%%%b\\%%' ==> 'a(.*)b\\%(.*)'
373
374 =item *
375
376 C<'greedy'>, when used in conjunction with C<'any'>, will make the C<'any'> captures greedy (by default they are not) ;
377
378     'a***b\\**' ==> 'a(.*?)b\\*(.*?)'
379     'a%%%b\\%%' ==> 'a(.*?)b\\%(.*?)'
380
381 =item *
382
383 C<'brackets'> will capture matching C<{ ... , ... }> alternations.
384
385     'a{b\\},\\{c}' ==> 'a(b\\}|\\{c)'
386
387 =back
388
389     $rw->capture(set => 'single');           # Only capture "exactly one" metacharacters.
390     $rw->capture('single');                  # Same.
391     $rw->capture(add => [ qw/any greedy/ ]); # Also greedily capture "any" metacharacters.
392     $rw->capture(rem => 'greedy');           # No more greed please.
393     $rw->capture();                          # Capture nothing.
394
395 =head2 C<convert $wc [ , $type ]>
396
397 Converts the wildcard expression C<$wc> into a regular expression according to the options stored into the L<Regexp::Wildcards> object, or to C<$type> if it's supplied.
398 It successively escapes all unprotected regexp special characters that doesn't hold any meaning for wildcards, then replace C<'jokers'> or C<'sql'> and C<'commas'> or C<'brackets'> (depending on the L</do> or L</type> options), all of this by applying the C<'capture'> rules specified in the constructor or by L</capture>.
399
400 =cut
401
402 sub convert {
403  my ($self, $wc, $type) = @_;
404  _check_self $self;
405  my $config;
406  if (defined $type) {
407   $config = $self->_type($type);
408  } else {
409   $config = $self;
410  }
411  return unless defined $wc;
412  my $do = $config->{do};
413  my $e  = $config->{escape};
414  $wc =~ s/(?<!\\)((?:\\\\)*[^\w\s\\$e])/\\$1/g;
415  if ($do->{jokers}) {
416   $wc = $self->_jokers($wc);
417  } elsif ($do->{sql}) {
418   $wc = $self->_sql($wc);
419  }
420  if ($do->{brackets}) {
421   $wc = $self->_bracketed($wc);
422  } elsif ($do->{commas}) {
423   if ($wc =~ /(?<!\\)(?:\\\\)*,/) { # win32 allows comma-separated lists
424    $wc = $self->{'c_brackets'} . $self->_commas($wc) . ')';
425   }
426  }
427  return $wc;
428 }
429
430 =head1 EXPORT
431
432 An object module shouldn't export any function, and so does this one.
433
434 =head1 DEPENDENCIES
435
436 L<Carp> (core module since perl 5), L<Text::Balanced> (since 5.7.3).
437
438 =head1 CAVEATS
439
440 This module does not implement the strange behaviours of Windows shell that result from the special handling of the three last characters (for the file extension).
441 For example, Windows XP shell matches C<*a> like C<.*a>, C<*a?> like C<.*a.?>, C<*a??> like C<.*a.{0,2}> and so on.
442
443 =head1 SEE ALSO
444
445 L<Text::Glob>.
446
447 =head1 AUTHOR
448
449 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
450
451 You can contact me by mail or on C<irc.perl.org> (vincent).
452
453 =head1 BUGS
454
455 Please report any bugs or feature requests to C<bug-regexp-wildcards at rt.cpan.org>, or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Regexp-Wildcards>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
456
457 =head1 SUPPORT
458
459 You can find documentation for this module with the perldoc command.
460
461     perldoc Regexp::Wildcards
462
463 Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Regexp-Wildcards>.
464
465 =head1 COPYRIGHT & LICENSE
466
467 Copyright 2007-2008 Vincent Pit, all rights reserved.
468
469 This program is free software; you can redistribute it and/or modify it
470 under the same terms as Perl itself.
471
472 =cut
473
474 sub _extract ($) { extract_bracketed $_[0], '{',  qr/.*?(?<!\\)(?:\\\\)*(?={)/ }
475
476 sub _jokers {
477  my $self = shift;
478  local $_ = $_[0];
479  # escape an odd number of \ that doesn't protect a regexp/wildcard special char
480  s/(?<!\\)((?:\\\\)*\\(?:[\w\s]|$))/\\$1/g;
481  # substitute ? preceded by an even number of \
482  my $s = $self->{c_single};
483  s/(?<!\\)((?:\\\\)*)\?/$1$s/g;
484  # substitute * preceded by an even number of \
485  $s = $self->{c_any};
486  s/(?<!\\)((?:\\\\)*)\*+/$1$s/g;
487  return $_;
488 }
489
490 sub _sql {
491  my $self = shift;
492  local $_ = $_[0];
493  # escape an odd number of \ that doesn't protect a regexp/wildcard special char
494  s/(?<!\\)((?:\\\\)*\\(?:[^\W_]|\s|$))/\\$1/g;
495  # substitute _ preceded by an even number of \
496  my $s = $self->{c_single};
497  s/(?<!\\)((?:\\\\)*)_/$1$s/g;
498  # substitute % preceded by an even number of \
499  $s = $self->{c_any};
500  s/(?<!\\)((?:\\\\)*)%+/$1$s/g;
501  return $_;
502 }
503
504 sub _commas {
505  local $_ = $_[1];
506  # substitute , preceded by an even number of \
507  s/(?<!\\)((?:\\\\)*),/$1|/g;
508  return $_;
509 }
510
511 sub _brackets {
512  my ($self, $rest) = @_;
513  substr $rest, 0, 1, '';
514  chop $rest;
515  my ($re, $bracket, $prefix) = ('');
516  while (do { ($bracket, $rest, $prefix) = _extract $rest; $bracket }) {
517   $re .= $self->_commas($prefix) . $self->_brackets($bracket);
518  }
519  $re .= $self->_commas($rest);
520  return $self->{c_brackets} . $re . ')';
521 }
522
523 sub _bracketed {
524  my ($self, $rest) = @_;
525  my ($re, $bracket, $prefix) = ('');
526  while (do { ($bracket, $rest, $prefix) = _extract $rest; $bracket }) {
527   $re .= $prefix . $self->_brackets($bracket);
528  }
529  $re .= $rest;
530  $re =~ s/(?<!\\)((?:\\\\)*[\{\},])/\\$1/g;
531  return $re;
532 }
533
534 1; # End of Regexp::Wildcards