]> git.vpit.fr Git - perl/modules/Regexp-Wildcards.git/blob - lib/Regexp/Wildcards.pm
Importing Regexp-Wildcards-0.08.tar.gz
[perl/modules/Regexp-Wildcards.git] / lib / Regexp / Wildcards.pm
1 package Regexp::Wildcards;
2
3 use strict;
4 use warnings;
5
6 use Text::Balanced qw/extract_bracketed/;
7
8 =head1 NAME
9
10 Regexp::Wildcards - Converts wildcard expressions to Perl regular expressions.
11
12 =head1 VERSION
13
14 Version 0.08
15
16 =cut
17
18 our $VERSION = '0.08';
19
20 =head1 SYNOPSIS
21
22     use Regexp::Wildcards qw/wc2re/;
23
24     my $re;
25     $re = wc2re 'a{b?,c}*' => 'unix';   # Do it Unix style.
26     $re = wc2re 'a?,b*'    => 'win32';  # Do it Windows style.
27     $re = wc2re '*{x,y}?'  => 'jokers'; # Process the jokers & escape the rest.
28     $re = wc2re '%a_c%'    => 'sql';    # Turn SQL wildcards into regexps.
29
30 =head1 DESCRIPTION
31
32 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. It handles the C<*> and C<?> shell jokers, as well as Unix bracketed alternatives C<{,}>, but also C<%> and C<_> SQL wildcards. Backspace (C<\>) is used as an escape character. Wrappers are provided to mimic the behaviour of Windows and Unix shells.
33
34 =head1 VARIABLES
35
36 These variables control if the wildcards jokers and brackets must capture their match. They can be globally set by writing in your program
37
38     $Regexp::Wildcards::CaptureSingle = 1;
39     # From then, "exactly one" wildcards are capturing
40
41 or can be locally specified via C<local>
42
43     {
44      local $Regexp::Wildcards::CaptureSingle = 1;
45      # In this block, "exactly one" wildcards are capturing.
46      ...
47     }
48     # Back to the situation from before the block
49
50 This section describes also how those elements are translated by the L<functions|/FUNCTIONS>.
51
52 =head2 C<$CaptureSingle>
53
54 When this variable is true, each occurence of unescaped I<"exactly one"> wildcards (i.e. C<?> jokers or C<_> for SQL wildcards) are made capturing in the resulting regexp (they are be replaced by C<(.)>). Otherwise, they are just replaced by C<.>. Default is the latter.
55
56     For jokers :
57     'a???b\\??' is translated to 'a(.)(.)(.)b\\?(.)' if $CaptureSingle is true
58                                  'a...b\\?.'         otherwise (default)
59
60     For SQL wildcards :
61     'a___b\\__' is translated to 'a(.)(.)(.)b\\_(.)' if $CaptureSingle is true
62                                  'a...b\\_.'         otherwise (default)
63
64 =cut
65
66 our $CaptureSingle = 0;
67
68 sub capture_single {
69  return $CaptureSingle ? '(.)'
70                        : '.';
71 }
72
73 =head2 C<$CaptureAny>
74
75 By default this variable is false, and successions of unescaped I<"any"> wildcards (i.e. C<*> jokers or C<%> for SQL wildcards) are replaced by B<one> single C<.*>. When it evalutes to true, those sequences of I<"any"> wildcards are made into B<one> capture, which is greedy (C<(.*)>) for C<$CaptureAny E<gt> 0> and otherwise non-greedy (C<(.*?)>).
76
77     For jokers :
78     'a***b\\**' is translated to 'a.*b\\*.*'       if $CaptureAny is false (default)
79                                  'a(.*)b\\*(.*)'   if $CaptureAny > 0
80                                  'a(.*?)b\\*(.*?)' otherwise
81
82     For SQL wildcards :
83     'a%%%b\\%%' is translated to 'a.*b\\%.*'       if $CaptureAny is false (default)
84                                  'a(.*)b\\%(.*)'   if $CaptureAny > 0
85                                  'a(.*?)b\\%(.*?)' otherwise
86
87 =cut
88
89 our $CaptureAny = 0;
90
91 sub capture_any {
92  return $CaptureAny ? (($CaptureAny > 0) ? '(.*)'
93                                          : '(.*?)')
94                     : '.*';
95 }
96
97 =head2 C<$CaptureBrackets>
98
99 If this variable is set to true, valid brackets constructs are made into C<( | )> captures, and otherwise they are replaced by non-capturing alternations (C<(?: | >)), which is the default.
100
101     'a{b\\},\\{c}' is translated to 'a(b\\}|\\{c)'   if $CaptureBrackets is true
102                                     'a(?:b\\}|\\{c)' otherwise (default)
103
104 =cut
105
106 our $CaptureBrackets = 0;
107
108 sub capture_brackets {
109  return $CaptureBrackets ? '('
110                          : '(?:';
111 }
112
113 =head1 FUNCTIONS
114
115 =head2 C<wc2re_jokers>
116
117 This function takes as its only argument the wildcard string to process, and returns the corresponding regular expression where the jokers C<?> (I<"exactly one">) and C<*> (I<"any">) have been translated into their regexp equivalents (see L</VARIABLES> for more details). All other unprotected regexp metacharacters are escaped.
118
119     # Everything is escaped.
120     print 'ok' if wc2re_jokers('{a{b,c}d,e}') eq '\\{a\\{b\\,c\\}d\\,e\\}';
121
122 =cut
123
124 sub wc2re_jokers {
125  my ($wc) = @_;
126  $wc =~ s/(?<!\\)((?:\\\\)*[^\w\s?*\\])/\\$1/g;
127  return do_jokers($wc);
128 }
129
130 =head2 C<wc2re_sql>
131
132 Similar to the precedent, but for the SQL wildcards C<_> (I<"exactly one">) and C<%> (I<"any">). All other unprotected regexp metacharacters are escaped.
133  
134 =cut
135   
136 sub wc2re_sql {
137  my ($wc) = @_;
138  $wc =~ s/(?<!\\)((?:\\\\)*[^\w\s%\\])/\\$1/g;
139  return do_sql($wc);
140 }
141
142 =head2 C<wc2re_unix>
143
144 This function conforms to standard Unix shell wildcard rules. It successively escapes all unprotected regexp special characters that doesn't hold any meaning for wildcards, turns C<?> and C<*> jokers into their regexp equivalents (see L</wc2re_jokers>), and changes bracketed blocks into (possibly capturing) alternations as described in L</VARIABLES>. If brackets are unbalanced, it tries to substitute as many of them as possible, and then escape the remaining C<{> and C<}>. Commas outside of any bracket-delimited block are also escaped.
145
146     # This is a valid bracket expression, and is completely translated.
147     print 'ok' if wc2re_unix('{a{b,c}d,e}') eq '(?:a(?:b|c)d|e)';
148
149 The function handles unbalanced bracket expressions, by escaping everything it can't recognize. For example :
150
151     # The first comma is replaced, and the remaining brackets and comma are escaped.
152     print 'ok' if wc2re_unix('{a\\{b,c}d,e}') eq '(?:a\\{b|c)d\\,e\\}';
153
154     # All the brackets and commas are escaped.
155     print 'ok' if wc2re_unix('{a{b,c\\}d,e}') eq '\\{a\\{b\\,c\\}d\\,e\\}';
156
157 =cut
158
159 sub wc2re_unix {
160  my ($re) = @_;
161  return unless defined $re;
162  $re =~ s/(?<!\\)((?:\\\\)*[^\w\s?*\\\{\},])/\\$1/g;
163  return do_bracketed(do_jokers($re));
164 }
165
166 =head2 C<wc2re_win32>
167
168 This one works just like the one before, but for Windows wildcards. Bracketed blocks are no longer handled (which means that brackets are escaped), but you can provide a comma-separated list of items.
169
170     # All the brackets are escaped, and commas are seen as list delimiters.
171     print 'ok' if wc2re_win32('{a{b,c}d,e}') eq '(?:\\{a\\{b|c\\}d|e\\})';
172
173 =cut
174
175 sub wc2re_win32 {
176  my ($wc) = @_;
177  return unless defined $wc;
178  $wc =~ s/(?<!\\)((?:\\\\)*[^\w\s?*\\,])/\\$1/g;
179  my $re = do_jokers($wc);
180  if ($re =~ /(?<!\\)(?:\\\\)*,/) { # win32 allows comma-separated lists
181   $re = capture_brackets . do_commas($re) . ')';
182  }
183  return $re;
184 }
185
186 =head2 C<wc2re>
187
188 A generic function that wraps around all the different rules. The first argument is the wildcard expression, and the second one is the type of rules to apply which can be :
189
190 =over 4
191
192 =item C<'unix'>, C<'win32'>, C<'jokers'>, C<'sql'>
193
194 For one of those raw rule names, C<wc2re> simply maps to C<wc2re_unix>, C<wc2re_win32>, C<wc2re_jokers> and C<wc2re_sql> respectively.
195
196 =item C<$^O>
197
198 If you supply the Perl operating system name, the call is deferred to C<wc2re_win32> for C< $^O> equal to C<'dos'>, C<'os2'>, C<'MSWin32'> or C<'cygwin'>, and to C<wc2re_unix> in all the other cases.
199
200 =back
201
202 If the type is undefined or not supported, it defaults to C<'unix'>.
203
204      # Wraps to wc2re_jokers ($re eq 'a\\{b\\,c\\}.*').
205      $re = wc2re 'a{b,c}*' => 'jokers';
206
207      # Wraps to wc2re_win32 ($re eq '(?:a\\{b|c\\}.*)')
208      #       or wc2re_unix  ($re eq 'a(?:b|c).*')       depending on $^O.
209      $re = wc2re 'a{b,c}*' => $^O;
210
211 =cut
212
213 my %types = (
214  'jokers'    => \&wc2re_jokers,
215  'sql'       => \&wc2re_sql,
216  'unix'      => \&wc2re_unix,
217  map { lc $_ => \&wc2re_win32 } qw/win32 dos os2 MSWin32 cygwin/
218 );
219
220 sub wc2re {
221  my ($wc, $type) = @_;
222  return unless defined $wc;
223  $type = $type ? lc $type : 'unix';
224  $type = 'unix' unless exists $types{$type};
225  return $types{$type}($wc);
226 }
227
228 =head1 EXPORT
229
230 These five functions are exported only on request : C<wc2re>, C<wc2re_unix>, C<wc2re_win32>, C<wc2re_jokers> and C<wc2re_sql>. The variables are not exported.
231
232 =cut
233
234 use base qw/Exporter/;
235
236 our @EXPORT         = ();
237 our %EXPORT_TAGS    = (
238  'funcs' =>  [ 'wc2re', map { 'wc2re_'.$_ } keys %types ],
239 );
240 our @EXPORT_OK      = map { @$_ } values %EXPORT_TAGS;
241 our @EXPORT_FAIL    = qw/extract/,
242                     (map { 'do_'.$_ } qw/jokers sql commas brackets bracketed/),
243                     (map { 'capture_'.$_ } qw/single any brackets/);
244 $EXPORT_TAGS{'all'} = [ @EXPORT_OK ];
245
246 =head1 DEPENDENCIES
247
248 L<Text::Balanced>, which is bundled with perl since version 5.7.3
249
250 =head1 CAVEATS
251
252 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.
253
254 =head1 SEE ALSO
255
256 Some modules provide incomplete alternatives as helper functions :
257
258 L<Net::FTPServer> has a method for that. Only jokers are translated, and escaping won't preserve them.
259
260 L<File::Find::Match::Util> has a C<wildcard> function that compiles a matcher. It only handles C<*>.
261
262 L<Text::Buffer> has the C<convertWildcardToRegex> class method that handles jokers.
263
264 =head1 AUTHOR
265
266 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
267
268 You can contact me by mail or on #perl @ FreeNode (vincent or Prof_Vince).
269
270 =head1 BUGS
271
272 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.
273
274 =head1 SUPPORT
275
276 You can find documentation for this module with the perldoc command.
277
278     perldoc Regexp::Wildcards
279
280 =head1 COPYRIGHT & LICENSE
281
282 Copyright 2007-2008 Vincent Pit, all rights reserved.
283
284 This program is free software; you can redistribute it and/or modify it
285 under the same terms as Perl itself.
286
287 =cut
288
289 sub extract { extract_bracketed shift, '{',  qr/.*?(?<!\\)(?:\\\\)*(?={)/; }
290
291 sub do_jokers {
292  local $_ = shift;
293  # escape an odd number of \ that doesn't protect a regexp/wildcard special char
294  s/(?<!\\)((?:\\\\)*\\(?:[\w\s]|$))/\\$1/g;
295  # substitute ? preceded by an even number of \
296  my $s = capture_single;
297  s/(?<!\\)((?:\\\\)*)\?/$1$s/g;
298  # substitute * preceded by an even number of \
299  $s = capture_any;
300  s/(?<!\\)((?:\\\\)*)\*+/$1$s/g;
301  return $_;
302 }
303
304 sub do_sql {
305  local $_ = shift;
306  # escape an odd number of \ that doesn't protect a regexp/wildcard special char
307  s/(?<!\\)((?:\\\\)*\\(?:[^\W_]|\s|$))/\\$1/g;
308  # substitute _ preceded by an even number of \
309  my $s = capture_single;
310  s/(?<!\\)((?:\\\\)*)_/$1$s/g;
311  # substitute * preceded by an even number of \
312  $s = capture_any;
313  s/(?<!\\)((?:\\\\)*)%+/$1$s/g;
314  return $_;
315 }
316
317 sub do_commas {
318  local $_ = shift;
319  # substitute , preceded by an even number of \
320  s/(?<!\\)((?:\\\\)*),/$1|/g;
321  return $_;
322 }
323
324 sub do_brackets {
325  my $rest = shift;
326  substr $rest, 0, 1, '';
327  chop $rest;
328  my ($re, $bracket, $prefix) = ('');
329  while (($bracket, $rest, $prefix) = extract $rest and $bracket) {
330   $re .= do_commas($prefix) . do_brackets($bracket);
331  }
332  $re .= do_commas($rest);
333  return capture_brackets . $re . ')';
334 }
335
336 sub do_bracketed {
337  my $rest = shift;
338  my ($re, $bracket, $prefix) = ('');
339  while (($bracket, $rest, $prefix) = extract $rest and $bracket) {
340   $re .= $prefix . do_brackets($bracket);
341  }
342  $re .= $rest;
343  $re =~ s/(?<!\\)((?:\\\\)*[\{\},])/\\$1/g;
344  return $re;
345 }
346
347 1; # End of Regexp::Wildcards