]> git.vpit.fr Git - perl/modules/Regexp-Wildcards.git/blob - lib/Regexp/Wildcards.pm
POD beautifications
[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.00
16
17 =cut
18
19 use vars qw/$VERSION/;
20 BEGIN {
21  $VERSION = '1.00';
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. Wildcards make one of those sets of simplified rules. This module converts wildcard expressions to Perl regular expressions, so that you can use them for matching.
49
50 It handles the C<*> and C<?> jokers, as well as Unix bracketed alternatives C<{,}>, but also C<%> and C<_> SQL wildcards. It can also keep original C<(...)> groups. Backspace (C<\>) is used as an escape character.
51
52 Typesets that mimic the behaviour of Windows and Unix shells are also provided.
53
54 =head1 METHODS
55
56 =cut
57
58 sub _check_self {
59  croak 'First argument isn\'t a valid ' . __PACKAGE__ . ' object'
60   unless ref $_[0] and $_[0]->isa(__PACKAGE__);
61 }
62
63 my %types = (
64  jokers   => [ qw/jokers/ ],
65  sql      => [ qw/sql/ ],
66  commas   => [ qw/commas/ ],
67  brackets => [ qw/brackets/ ],
68  unix     => [ qw/jokers brackets/ ],
69  win32    => [ qw/jokers commas/ ],
70 );
71 $types{$_} = $types{win32} for qw/dos os2 MSWin32 cygwin/;
72
73 my %escapes = (
74  jokers   => '?*',
75  sql      => '_%',
76  commas   => ',',
77  brackets => '{},',
78  groups   => '()',
79 );
80
81 my %captures = (
82  single   => sub { $_[1] ? '(.)' : '.' },
83  any      => sub { $_[1] ? ($_[0]->{greedy} ? '(.*)'
84                                             : '(.*?)')
85                          : '.*' },
86  brackets => sub { $_[1] ? '(' : '(?:'; },
87  greedy   => undef
88 );
89
90 sub _validate {
91  my $self  = shift;
92  _check_self $self;
93  my $valid = shift;
94  my $old   = shift;
95  $old = { } unless defined $old;
96  my $c;
97  if (@_ <= 1) {
98   $c = { set => $_[0] };
99  } elsif (@_ % 2) {
100   croak 'Arguments must be passed as an unique scalar or as key => value pairs';
101  } else {
102   my %args = @_;
103   $c = { map { (exists $args{$_}) ? ($_ => $args{$_}) : () } qw/set add rem/ };
104  }
105  for (qw/set add rem/) {
106   my $v = $c->{$_};
107   next unless defined $v;
108   my $cb = {
109    ''      => sub { +{ ($_[0] => 1) x (exists $valid->{$_[0]}) } },
110    'ARRAY' => sub { +{ map { ($_ => 1) x (exists $valid->{$_}) } @{$_[0]} } },
111    'HASH'  => sub { +{ map { ($_ => $_[0]->{$_}) x (exists $valid->{$_}) }
112                         keys %{$_[0]} } }
113   }->{ ref $v };
114   croak 'Wrong option set' unless $cb;
115   $c->{$_} = $cb->($v);
116  }
117  my $config = (exists $c->{set}) ? $c->{set} : $old;
118  $config->{$_} = $c->{add}->{$_} for grep $c->{add}->{$_},
119                                                 keys %{$c->{add} || {}};
120  delete $config->{$_} for grep $c->{rem}->{$_}, keys %{$c->{rem} || {}};
121  $config;
122 }
123
124 sub _do {
125  my $self = shift;
126  my $config;
127  $config->{do} = $self->_validate(\%escapes, $self->{do}, @_);
128  $config->{escape} = '';
129  $config->{escape} .= $escapes{$_} for keys %{$config->{do}};
130  $config->{escape} = quotemeta $config->{escape};
131  $config;
132 }
133
134 sub do {
135  my $self = shift;
136  _check_self $self;
137  my $config = $self->_do(@_);
138  $self->{$_} = $config->{$_} for keys %$config;
139  $self;
140 }
141
142 sub _capture {
143  my $self = shift;
144  my $config;
145  $config->{capture} = $self->_validate(\%captures, $self->{capture}, @_);
146  $config->{greedy}  = delete $config->{capture}->{greedy};
147  for (keys %captures) {
148   $config->{'c_' . $_} = $captures{$_}->($config, $config->{capture}->{$_})
149                                                if $captures{$_}; # Skip 'greedy'
150  }
151  $config;
152 }
153
154 sub capture {
155  my $self = shift;
156  _check_self $self;
157  my $config = $self->_capture(@_);
158  $self->{$_} = $config->{$_} for keys %$config;
159  $self;
160 }
161
162 sub _type {
163  my ($self, $type) = @_;
164  $type = 'unix'      unless defined $type;
165  croak 'Wrong type'  unless exists $types{$type};
166  my $config = $self->_do($types{$type});
167  $config->{type} = $type;
168  $config;
169 }
170
171 sub type {
172  my $self = shift;
173  _check_self $self;
174  my $config = $self->_type(@_);
175  $self->{$_} = $config->{$_} for keys %$config;
176  $self;
177 }
178
179 sub new {
180  my $class = shift;
181  $class = ref($class) || $class || __PACKAGE__;
182  croak 'Optional arguments must be passed as key => value pairs' if @_ % 2;
183  my %args = @_;
184  my $self = { };
185  bless $self, $class;
186  if (defined $args{do}) {
187   $self->do($args{do});
188  } else {
189   $self->type($args{type});
190  }
191  $self->capture($args{capture});
192 }
193
194 =head2 C<< new [ do => $what E<verbar> type => $type ], capture => $captures >>
195
196 Constructs a new L<Regexp::Wildcard> object.
197
198 C<do> lists all features that should be enabled when converting wildcards to regexps. Refer to L</do> for details on what can be passed in C<$what>.
199
200 The C<type> specifies a predefined set of C<do> features to use. See L</type> for details on which types are valid. The C<do> option overrides C<type>.
201
202 C<capture> lists which atoms should be capturing. Refer to L</capture> for more details.
203
204 =head2 C<< do [ $what E<verbar> set => $c1, add => $c2, rem => $c3 ] >>
205
206 Specifies the list of metacharacters to convert.
207 They are classified into five classes :
208
209 =over 4
210
211 =item *
212
213 C<'jokers'> converts C<?> to C<.> and C<*> to C<.*> ;
214
215     'a**\\*b??\\?c' ==> 'a.*\\*b..\\?c'
216
217 =item *
218
219 C<'sql'> converts C<_> to C<.> and C<%> to C<.*> ;
220
221     'a%%\\%b__\\_c' ==> 'a.*\\%b..\\_c'
222
223 =item *
224
225 C<'commas'> converts all C<,> to C<|> and puts the complete resulting regular expression inside C<(?: ... )> ;
226
227     'a,b{c,d},e' ==> '(?:a|b\\{c|d\\}|e)'
228
229 =item *
230
231 C<'brackets'> converts all matching C<{ ... ,  ... }> brackets to C<(?: ... | ... )> alternations. If some brackets are unbalanced, it tries to substitute as many of them as possible, and then escape the remaining unmatched C<{> and C<}>. Commas outside of any bracket-delimited block are also escaped ;
232
233     'a,b{c,d},e'    ==> 'a\\,b(?:c|d)\\,e'
234     '{a\\{b,c}d,e}' ==> '(?:a\\{b|c)d\\,e\\}'
235     '{a{b,c\\}d,e}' ==> '\\{a\\{b\\,c\\}d\\,e\\}'
236
237 =item *
238
239 C<'groups'> keeps the parenthesis C<( ... )> of the original string without escaping them. Currently, no check is done to ensure that the parenthesis are matching.
240
241     'a(b(c))d\\(\\)' ==> (no change)
242
243 =back
244
245 Each C<$c> can be any of :
246
247 =over 4
248
249 =item *
250
251 A hash reference, with wanted metacharacter group names (described above) as keys and booleans as values ;
252
253 =item *
254
255 An array reference containing the list of wanted metacharacter classes ;
256
257 =item *
258
259 A plain scalar, when only one group is required.
260
261 =back
262
263 When C<set> is present, the classes given as its value replace the current object options. Then the C<add> classes are added, and the C<rem> classes removed.
264
265 Passing a sole scalar C<$what> is equivalent as passing C<< set => $what >>.
266 No argument means C<< set => [ ] >>.
267
268     $rw->do(set => 'jokers');           # Only translate jokers.
269     $rw->do('jokers');                  # Same.
270     $rw->do(add => [ qw/sql commas/ ]); # Translate also SQL and commas.
271     $rw->do(rem => 'jokers');           # Specifying both 'sql' and 'jokers' is useless.
272     $rw->do();                          # Translate nothing.
273
274 =head2 C<type $type>
275
276 Notifies to convert the metacharacters that corresponds to the predefined type C<$type>. C<$type> can be any of C<'jokers'>, C<'sql'>, C<'commas'>, C<'brackets'>, C<'win32'> or C<'unix'>. An unknown or undefined value defaults to C<'unix'>, except for C<'dos'>, C<'os2'>, C<'MSWin32'> and C<'cygwin'> that default to C<'win32'>. This means that you can pass C<$^O> as the C<$type> and get the corresponding shell behaviour. Returns the object.
277
278     $rw->type('win32'); # Set type to win32.
279     $rw->type();        # Set type to unix.
280
281 =head2 C<< capture [ $captures E<verbar> set => $c1, add => $c2, rem => $c3 ] >>
282
283 Specifies the list of atoms to capture.
284 This method works like L</do>, except that the classes are different :
285
286 =over 4
287
288 =item *
289
290 C<'single'> will capture all unescaped I<"exactly one"> metacharacters, i.e. C<?> for wildcards or C<_> for SQL ;
291
292     'a???b\\??' ==> 'a(.)(.)(.)b\\?(.)'
293     'a___b\\__' ==> 'a(.)(.)(.)b\\_(.)'
294
295 =item *
296
297 C<'any'> will capture all unescaped I<"any"> metacharacters, i.e. C<*> for wildcards or C<%> for SQL ;
298
299     'a***b\\**' ==> 'a(.*)b\\*(.*)'
300     'a%%%b\\%%' ==> 'a(.*)b\\%(.*)'
301
302 =item *
303
304 C<'greedy'>, when used in conjunction with C<'any'>, will make the C<'any'> captures greedy (by default they are not) ;
305
306     'a***b\\**' ==> 'a(.*?)b\\*(.*?)'
307     'a%%%b\\%%' ==> 'a(.*?)b\\%(.*?)'
308
309 =item *
310
311 C<'brackets'> will capture matching C<{ ... , ... }> alternations.
312
313     'a{b\\},\\{c}' ==> 'a(b\\}|\\{c)'
314
315 =back
316
317     $rw->capture(set => 'single');           # Only capture "exactly one" metacharacters.
318     $rw->capture('single');                  # Same.
319     $rw->capture(add => [ qw/any greedy/ ]); # Also greedily capture "any" metacharacters.
320     $rw->capture(rem => 'greedy');           # No more greed please.
321     $rw->capture();                          # Capture nothing.
322
323 =head2 C<convert $wc [ , $type ]>
324
325 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. 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>.
326
327 =cut
328
329 sub convert {
330  my ($self, $wc, $type) = @_;
331  _check_self $self;
332  my $config;
333  if (defined $type) {
334   $config = $self->_type($type);
335  } else {
336   $config = $self;
337  }
338  return unless defined $wc;
339  my $do = $config->{do};
340  my $e  = $config->{escape};
341  $wc =~ s/(?<!\\)((?:\\\\)*[^\w\s\\$e])/\\$1/g;
342  return $self->_sql($wc)   if $do->{sql};
343  $wc = $self->_jokers($wc) if $do->{jokers};
344  if ($do->{brackets}) {
345   $wc = $self->_bracketed($wc);
346  } elsif ($do->{commas}) {
347   if ($wc =~ /(?<!\\)(?:\\\\)*,/) { # win32 allows comma-separated lists
348    $wc = $self->{'c_brackets'} . $self->_commas($wc) . ')';
349   }
350  }
351  return $wc;
352 }
353
354 =head1 EXPORT
355
356 An object module shouldn't export any function, and so does this one.
357
358 =head1 DEPENDENCIES
359
360 L<Carp> (core module since perl 5), L<Text::Balanced> (since 5.7.3).
361
362 =head1 CAVEATS
363
364 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). 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.
365
366 =head1 AUTHOR
367
368 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
369
370 You can contact me by mail or on #perl @ FreeNode (vincent or Prof_Vince).
371
372 =head1 BUGS
373
374 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.
375
376 =head1 SUPPORT
377
378 You can find documentation for this module with the perldoc command.
379
380     perldoc Regexp::Wildcards
381
382 Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Regexp-Wildcards>.
383
384 =head1 COPYRIGHT & LICENSE
385
386 Copyright 2007-2008 Vincent Pit, all rights reserved.
387
388 This program is free software; you can redistribute it and/or modify it
389 under the same terms as Perl itself.
390
391 =cut
392
393 sub _extract ($) { extract_bracketed $_[0], '{',  qr/.*?(?<!\\)(?:\\\\)*(?={)/ }
394
395 sub _jokers {
396  my $self = shift;
397  local $_ = $_[0];
398  # escape an odd number of \ that doesn't protect a regexp/wildcard special char
399  s/(?<!\\)((?:\\\\)*\\(?:[\w\s]|$))/\\$1/g;
400  # substitute ? preceded by an even number of \
401  my $s = $self->{c_single};
402  s/(?<!\\)((?:\\\\)*)\?/$1$s/g;
403  # substitute * preceded by an even number of \
404  $s = $self->{c_any};
405  s/(?<!\\)((?:\\\\)*)\*+/$1$s/g;
406  return $_;
407 }
408
409 sub _sql {
410  my $self = shift;
411  local $_ = $_[0];
412  # escape an odd number of \ that doesn't protect a regexp/wildcard special char
413  s/(?<!\\)((?:\\\\)*\\(?:[^\W_]|\s|$))/\\$1/g;
414  # substitute _ preceded by an even number of \
415  my $s = $self->{c_single};
416  s/(?<!\\)((?:\\\\)*)_/$1$s/g;
417  # substitute % preceded by an even number of \
418  $s = $self->{c_any};
419  s/(?<!\\)((?:\\\\)*)%+/$1$s/g;
420  return $_;
421 }
422
423 sub _commas {
424  local $_ = $_[1];
425  # substitute , preceded by an even number of \
426  s/(?<!\\)((?:\\\\)*),/$1|/g;
427  return $_;
428 }
429
430 sub _brackets {
431  my ($self, $rest) = @_;
432  substr $rest, 0, 1, '';
433  chop $rest;
434  my ($re, $bracket, $prefix) = ('');
435  while (do { ($bracket, $rest, $prefix) = _extract $rest; $bracket }) {
436   $re .= $self->_commas($prefix) . $self->_brackets($bracket);
437  }
438  $re .= $self->_commas($rest);
439  return $self->{c_brackets} . $re . ')';
440 }
441
442 sub _bracketed {
443  my ($self, $rest) = @_;
444  my ($re, $bracket, $prefix) = ('');
445  while (do { ($bracket, $rest, $prefix) = _extract $rest; $bracket }) {
446   $re .= $prefix . $self->_brackets($bracket);
447  }
448  $re .= $rest;
449  $re =~ s/(?<!\\)((?:\\\\)*[\{\},])/\\$1/g;
450  return $re;
451 }
452
453 1; # End of Regexp::Wildcards