]> git.vpit.fr Git - perl/modules/Regexp-Wildcards.git/blob - lib/Regexp/Wildcards.pm
Switch to qw<>
[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.03
16
17 =cut
18
19 use vars qw<$VERSION>;
20 BEGIN {
21  $VERSION = '1.03';
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
108  my %opts;
109  if (@_ <= 1) {
110   $opts{set} = defined $_[0] ? $_[0] : { };
111  } elsif (@_ % 2) {
112   croak 'Arguments must be passed as an unique scalar or as key => value pairs';
113  } else {
114   %opts = @_;
115  }
116
117  my %checked;
118  for (qw<set add rem>) {
119   my $opt = $opts{$_};
120   next unless defined $opt;
121   my $cb = {
122    ''      => sub { +{ ($_[0] => 1) x (exists $valid->{$_[0]}) } },
123    'ARRAY' => sub { +{ map { ($_ => 1) x (exists $valid->{$_}) } @{$_[0]} } },
124    'HASH'  => sub { +{ map { ($_ => $_[0]->{$_}) x (exists $valid->{$_}) }
125                         keys %{$_[0]} } }
126   }->{ ref $opt };
127   croak 'Wrong option set' unless $cb;
128   $checked{$_} = $cb->($opt);
129  }
130
131  my $config = (exists $checked{set}) ? $checked{set} : $old;
132  $config->{$_} = $checked{add}->{$_} for grep $checked{add}->{$_},
133                                           keys %{$checked{add} || {}};
134  delete $config->{$_}                for grep $checked{rem}->{$_},
135                                           keys %{$checked{rem} || {}};
136
137  $config;
138 }
139
140 sub _do {
141  my $self = shift;
142  my $config;
143  $config->{do} = $self->_validate(\%escapes, $self->{do}, @_);
144  $config->{escape} = '';
145  $config->{escape} .= $escapes{$_} for keys %{$config->{do}};
146  $config->{escape} = quotemeta $config->{escape};
147  $config;
148 }
149
150 sub do {
151  my $self = shift;
152  _check_self $self;
153  my $config = $self->_do(@_);
154  $self->{$_} = $config->{$_} for keys %$config;
155  $self;
156 }
157
158 sub _capture {
159  my $self = shift;
160  my $config;
161  $config->{capture} = $self->_validate(\%captures, $self->{capture}, @_);
162  $config->{greedy}  = delete $config->{capture}->{greedy};
163  for (keys %captures) {
164   $config->{'c_' . $_} = $captures{$_}->($config, $config->{capture}->{$_})
165                                                if $captures{$_}; # Skip 'greedy'
166  }
167  $config;
168 }
169
170 sub capture {
171  my $self = shift;
172  _check_self $self;
173  my $config = $self->_capture(@_);
174  $self->{$_} = $config->{$_} for keys %$config;
175  $self;
176 }
177
178 sub _type {
179  my ($self, $type) = @_;
180  $type = 'unix'      unless defined $type;
181  croak 'Wrong type'  unless exists $types{$type};
182  my $config = $self->_do($types{$type});
183  $config->{type} = $type;
184  $config;
185 }
186
187 sub type {
188  my $self = shift;
189  _check_self $self;
190  my $config = $self->_type(@_);
191  $self->{$_} = $config->{$_} for keys %$config;
192  $self;
193 }
194
195 sub new {
196  my $class = shift;
197  $class = ref($class) || $class || __PACKAGE__;
198  croak 'Optional arguments must be passed as key => value pairs' if @_ % 2;
199  my %args = @_;
200  my $self = { };
201  bless $self, $class;
202  if (defined $args{do}) {
203   $self->do($args{do});
204  } else {
205   $self->type($args{type});
206  }
207  $self->capture($args{capture});
208 }
209
210 =head2 C<< new [ do => $what E<verbar> type => $type ], capture => $captures >>
211
212 Constructs a new L<Regexp::Wildcard> object.
213
214 C<do> lists all features that should be enabled when converting wildcards to regexps.
215 Refer to L</do> for details on what can be passed in C<$what>.
216
217 The C<type> specifies a predefined set of C<do> features to use.
218 See L</type> for details on which types are valid.
219 The C<do> option overrides C<type>.
220
221 C<capture> lists which atoms should be capturing.
222 Refer to L</capture> for more details.
223
224 =head2 C<< do [ $what E<verbar> set => $c1, add => $c2, rem => $c3 ] >>
225
226 Specifies the list of metacharacters to convert or to prevent for escaping.
227 They fit into six classes :
228
229 =over 4
230
231 =item *
232
233 C<'jokers'>
234
235 Converts C<?> to C<.> and C<*> to C<.*>.
236
237     'a**\\*b??\\?c' ==> 'a.*\\*b..\\?c'
238
239 =item *
240
241 C<'sql'>
242
243 Converts C<_> to C<.> and C<%> to C<.*>.
244
245     'a%%\\%b__\\_c' ==> 'a.*\\%b..\\_c'
246
247 =item *
248
249 C<'commas'>
250
251 Converts all C<,> to C<|> and puts the complete resulting regular expression inside C<(?: ... )>.
252
253     'a,b{c,d},e' ==> '(?:a|b\\{c|d\\}|e)'
254
255 =item *
256
257 C<'brackets'>
258
259 Converts all matching C<{ ... ,  ... }> brackets to C<(?: ... | ... )> alternations.
260 If some brackets are unbalanced, it tries to substitute as many of them as possible, and then escape the remaining unmatched C<{> and C<}>.
261 Commas outside of any bracket-delimited block are also escaped.
262
263     'a,b{c,d},e'    ==> 'a\\,b(?:c|d)\\,e'
264     '{a\\{b,c}d,e}' ==> '(?:a\\{b|c)d\\,e\\}'
265     '{a{b,c\\}d,e}' ==> '\\{a\\{b\\,c\\}d\\,e\\}'
266
267 =item *
268
269 C<'groups'>
270
271 Keeps the parenthesis C<( ... )> of the original string without escaping them.
272 Currently, no check is done to ensure that the parenthesis are matching.
273
274     'a(b(c))d\\(\\)' ==> (no change)
275
276 =item *
277
278 C<'anchors'>
279
280 Prevents the I<beginning-of-line> C<^> and I<end-of-line> C<$> anchors to be escaped.
281 Since C<[...]> character class are currently escaped, a C<^> will always be interpreted as I<beginning-of-line>.
282
283     'a^b$c' ==> (no change)
284
285 =back
286
287 Each C<$c> can be any of :
288
289 =over 4
290
291 =item *
292
293 A hash reference, with wanted metacharacter group names (described above) as keys and booleans as values ;
294
295 =item *
296
297 An array reference containing the list of wanted metacharacter classes ;
298
299 =item *
300
301 A plain scalar, when only one group is required.
302
303 =back
304
305 When C<set> is present, the classes given as its value replace the current object options.
306 Then the C<add> classes are added, and the C<rem> classes removed.
307
308 Passing a sole scalar C<$what> is equivalent as passing C<< set => $what >>.
309 No argument means C<< set => [ ] >>.
310
311     $rw->do(set => 'jokers');           # Only translate jokers.
312     $rw->do('jokers');                  # Same.
313     $rw->do(add => [ qw<sql commas> ]); # Translate also SQL and commas.
314     $rw->do(rem => 'jokers');           # Specifying both 'sql' and 'jokers' is useless.
315     $rw->do();                          # Translate nothing.
316
317 The C<do> method returns the L<Regexp::Wildcards> object.
318
319 =head2 C<type $type>
320
321 Notifies to convert the metacharacters that corresponds to the predefined type C<$type>.
322 C<$type> can be any of :
323
324 =over 4
325
326 =item *
327
328 C<'jokers'>, C<'sql'>, C<'commas'>, C<'brackets'>
329
330 Singleton types that enable the corresponding C<do> classes.
331
332 =item *
333
334 C<'unix'>
335
336 Covers typical Unix shell globbing features (effectively C<'jokers'> and C<'brackets'>).
337
338 =item *
339
340 C<$^O> values for common Unix systems
341
342 Wrap to C<'unix'> (see L<perlport> for the list).
343
344 =item *
345
346 C<undef>
347
348 Defaults to C<'unix'>.
349
350 =item *
351
352 C<'win32'>
353
354 Covers typical Windows shell globbing features (effectively C<'jokers'> and C<'commas'>).
355
356 =item *
357
358 C<'dos'>, C<'os2'>, C<'MSWin32'>, C<'cygwin'>
359
360 Wrap to C<'win32'>.
361
362 =back
363
364 In particular, you can usually pass C<$^O> as the C<$type> and get the corresponding shell behaviour.
365
366     $rw->type('win32'); # Set type to win32.
367     $rw->type($^O);     # Set type to unix on Unices and win32 on Windows
368     $rw->type();        # Set type to unix.
369
370 The C<type> method returns the L<Regexp::Wildcards> object.
371
372 =head2 C<< capture [ $captures E<verbar> set => $c1, add => $c2, rem => $c3 ] >>
373
374 Specifies the list of atoms to capture.
375 This method works like L</do>, except that the classes are different :
376
377 =over 4
378
379 =item *
380
381 C<'single'>
382
383 Captures all unescaped I<"exactly one"> metacharacters, i.e. C<?> for wildcards or C<_> for SQL.
384
385     'a???b\\??' ==> 'a(.)(.)(.)b\\?(.)'
386     'a___b\\__' ==> 'a(.)(.)(.)b\\_(.)'
387
388 =item *
389
390 C<'any'>
391
392 Captures all unescaped I<"any"> metacharacters, i.e. C<*> for wildcards or C<%> for SQL.
393
394     'a***b\\**' ==> 'a(.*)b\\*(.*)'
395     'a%%%b\\%%' ==> 'a(.*)b\\%(.*)'
396
397 =item *
398
399 C<'greedy'>
400
401 When used in conjunction with C<'any'>, it makes the C<'any'> captures greedy (by default they are not).
402
403     'a***b\\**' ==> 'a(.*?)b\\*(.*?)'
404     'a%%%b\\%%' ==> 'a(.*?)b\\%(.*?)'
405
406 =item *
407
408 C<'brackets'>
409
410 Capture matching C<{ ... , ... }> alternations.
411
412     'a{b\\},\\{c}' ==> 'a(b\\}|\\{c)'
413
414 =back
415
416     $rw->capture(set => 'single');           # Only capture "exactly one" metacharacters.
417     $rw->capture('single');                  # Same.
418     $rw->capture(add => [ qw<any greedy> ]); # Also greedily capture "any" metacharacters.
419     $rw->capture(rem => 'greedy');           # No more greed please.
420     $rw->capture();                          # Capture nothing.
421
422 The C<capture> method returns the L<Regexp::Wildcards> object.
423
424 =head2 C<convert $wc [ , $type ]>
425
426 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.
427 It successively escapes all unprotected regexp special characters that doesn't hold any meaning for wildcards, then replace C<'jokers'>, 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>.
428
429 =cut
430
431 sub convert {
432  my ($self, $wc, $type) = @_;
433  _check_self $self;
434  my $config = (defined $type) ? $self->_type($type) : $self;
435  return unless defined $wc;
436
437  my $e = $config->{escape};
438  # Escape :
439  # - an even number of \ that doesn't protect a regexp/wildcard metachar
440  # - an odd number of \ that doesn't protect a wildcard metachar
441  $wc =~ s/
442   (?<!\\)(
443    (?:\\\\)*
444    (?:
445      [^\w\s\\$e]
446     |
447      \\
448      (?: [^\W$e] | \s | $ )
449    )
450   )
451  /\\$1/gx;
452
453  my $do = $config->{do};
454  $wc = $self->_jokers($wc) if $do->{jokers};
455  $wc = $self->_sql($wc)    if $do->{sql};
456  if ($do->{brackets}) {
457   $wc = $self->_bracketed($wc);
458  } elsif ($do->{commas} and $wc =~ /(?<!\\)(?:\\\\)*,/) {
459   $wc = $self->{'c_brackets'} . $self->_commas($wc) . ')';
460  }
461
462  return $wc;
463 }
464
465 =head1 EXPORT
466
467 An object module shouldn't export any function, and so does this one.
468
469 =head1 DEPENDENCIES
470
471 L<Carp> (core module since perl 5), L<Text::Balanced> (since 5.7.3).
472
473 =head1 CAVEATS
474
475 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).
476 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.
477
478 =head1 SEE ALSO
479
480 L<Text::Glob>.
481
482 =head1 AUTHOR
483
484 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
485
486 You can contact me by mail or on C<irc.perl.org> (vincent).
487
488 =head1 BUGS
489
490 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.
491
492 =head1 SUPPORT
493
494 You can find documentation for this module with the perldoc command.
495
496     perldoc Regexp::Wildcards
497
498 Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Regexp-Wildcards>.
499
500 =head1 COPYRIGHT & LICENSE
501
502 Copyright 2007-2009 Vincent Pit, all rights reserved.
503
504 This program is free software; you can redistribute it and/or modify it
505 under the same terms as Perl itself.
506
507 =cut
508
509 sub _extract ($) { extract_bracketed $_[0], '{',  qr/.*?(?<!\\)(?:\\\\)*(?={)/ }
510
511 sub _jokers {
512  my $self = shift;
513  local $_ = $_[0];
514  # substitute ? preceded by an even number of \
515  my $s = $self->{c_single};
516  s/(?<!\\)((?:\\\\)*)\?/$1$s/g;
517  # substitute * preceded by an even number of \
518  $s = $self->{c_any};
519  s/(?<!\\)((?:\\\\)*)\*+/$1$s/g;
520  return $_;
521 }
522
523 sub _sql {
524  my $self = shift;
525  local $_ = $_[0];
526  # substitute _ preceded by an even number of \
527  my $s = $self->{c_single};
528  s/(?<!\\)((?:\\\\)*)_/$1$s/g;
529  # substitute % preceded by an even number of \
530  $s = $self->{c_any};
531  s/(?<!\\)((?:\\\\)*)%+/$1$s/g;
532  return $_;
533 }
534
535 sub _commas {
536  local $_ = $_[1];
537  # substitute , preceded by an even number of \
538  s/(?<!\\)((?:\\\\)*),/$1|/g;
539  return $_;
540 }
541
542 sub _brackets {
543  my ($self, $rest) = @_;
544  substr $rest, 0, 1, '';
545  chop $rest;
546  my ($re, $bracket, $prefix) = ('');
547  while (do { ($bracket, $rest, $prefix) = _extract $rest; $bracket }) {
548   $re .= $self->_commas($prefix) . $self->_brackets($bracket);
549  }
550  $re .= $self->_commas($rest);
551  return $self->{c_brackets} . $re . ')';
552 }
553
554 sub _bracketed {
555  my ($self, $rest) = @_;
556  my ($re, $bracket, $prefix) = ('');
557  while (do { ($bracket, $rest, $prefix) = _extract $rest; $bracket }) {
558   $re .= $prefix . $self->_brackets($bracket);
559  }
560  $re .= $rest;
561  $re =~ s/(?<!\\)((?:\\\\)*[\{\},])/\\$1/g;
562  return $re;
563 }
564
565 1; # End of Regexp::Wildcards