]> git.vpit.fr Git - perl/modules/Regexp-Wildcards.git/blob - lib/Regexp/Wildcards.pm
Importing Regexp-Wildcards-0.04.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.04
15
16 =cut
17
18 our $VERSION = '0.04';
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
29 =head1 DESCRIPTION
30
31 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<?> jokers, as well as Unix bracketed alternatives C<{,}>, and uses the backspace (C<\>) as an escape character. Wrappers are provided to mimic the behaviour of Windows and Unix shells.
32
33 =head1 VARIABLES
34
35 These variables control if the wildcards jokers and brackets must capture their match. They can be globally set by writing in your program
36
37     $Regexp::Wildcards::CaptureAny = -1;
38     # From then, '*' jokers are capturing
39
40 or can be locally specified via C<local>
41
42     {
43      local $Regexp::Wildcards::CaptureAny = -1;
44      # In this block, the '*' joker is capturing.
45      ...
46     }
47     # Back to the situation from before the block
48
49 This section describes also how those elements are translated by the L<functions|/FUNCTIONS>.
50
51 =head2 C<$CaptureSingle>
52
53 When this variable is true, each occurence of the unescaped C<?> joker is made capturing in the resulting regexp (they are be replaced by C<(.)>). Otherwise, they are just replaced by C<.>. Default is the latter.
54
55     'a???b\\??' is translated to 'a(.)(.)(.)b\\?(.)' if $CaptureSingle is true
56                                  'a...b\\?.'         otherwise (default)
57
58 =cut
59
60 our $CaptureSingle = 0;
61
62 =head2 C<$CaptureAny>
63
64 By default this variable is false, and successions of unescaped C<*> jokers are replaced by B<one> single C<.*>. When it evalutes to true, those sequences of C<*> are made into B<one> capture, which is greedy (C<(.*)>) for C<$CaptureAny E<gt> 0> and otherwise non-greedy (C<(.*?)>).
65
66     'a***b\\**' is translated to 'a.*b\\*.*'       if $CaptureAny is false (default)
67                                  'a(.*)b\\*(.*)'   if $CaptureAny > 0
68                                  'a(.*?)b\\*(.*?)' otherwise
69
70 =cut
71
72 our $CaptureAny = 0;
73
74 =head2 C<$CaptureBrackets>
75
76 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.
77
78     'a{b\\},\\{c}' is translated to 'a(b\\}|\\{c)'   if $CaptureBrackets is true
79                                     'a(?:b\\}|\\{c)' otherwise (default)
80
81 =cut
82
83 our $CaptureBrackets = 0;
84
85 =head1 FUNCTIONS
86
87 =head2 C<wc2re_jokers>
88
89 This function takes as its only argument the wildcard string to process, and returns the corresponding regular expression where the jokers C<?> and C<*> have been translated into their regexp equivalents (see L</VARIABLES> for more details). All other unprotected regexp metacharacters are escaped.
90
91     # Everything is escaped.
92     print 'ok' if wc2re_jokers('{a{b,c}d,e}') eq '\\{a\\{b\\,c\\}d\\,e\\}';
93
94 =cut
95
96 sub wc2re_jokers {
97  my ($wc) = @_;
98  $wc =~ s/(?<!\\)((?:\\\\)*[^\w\s?*\\])/\\$1/g;
99  return do_jokers($wc);
100 }
101
102 =head2 C<wc2re_unix>
103
104 Similar to the precedent, but this one conforms to standard Unix shell wildcard rules. It successively escapes all unprotected regexp special characters that doesn't hold any meaning for wildcards, turns 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.
105
106     # This is a valid bracket expression, and is completely translated.
107     print 'ok' if wc2re_unix('{a{b,c}d,e}') eq '(?:a(?:b|c)d|e)';
108
109 The function handles unbalanced bracket expressions, by escaping everything it can't recognize. For example :
110
111     # The first comma is replaced, and the remaining brackets and comma are escaped.
112     print 'ok' if wc2re_unix('{a\\{b,c}d,e}') eq '(?:a\\{b|c)d\\,e\\}';
113
114     # All the brackets and commas are escaped.
115     print 'ok' if wc2re_unix('{a{b,c\\}d,e}') eq '\\{a\\{b\\,c\\}d\\,e\\}';
116
117 =cut
118
119 sub wc2re_unix {
120  my ($re) = @_;
121  return unless defined $re;
122  $re =~ s/(?<!\\)((?:\\\\)*[^\w\s?*\\\{\},])/\\$1/g;
123  return do_bracketed(do_jokers($re));
124 }
125
126 =head2 C<wc2re_win32>
127
128 This one works just like the two 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.
129
130     # All the brackets are escaped, and commas are seen as list delimiters.
131     print 'ok' if wc2re_win32('{a{b,c}d,e}') eq '(?:\\{a\\{b|c\\}d|e\\})';
132
133 =cut
134
135 sub wc2re_win32 {
136  my ($wc) = @_;
137  return unless defined $wc;
138  $wc =~ s/(?<!\\)((?:\\\\)*[^\w\s?*\\,])/\\$1/g;
139  my $re = do_jokers($wc);
140  if ($re =~ /(?<!\\)(?:\\\\)*,/) { # win32 allows comma-separated lists
141   $re = ($CaptureBrackets ? '(' : '(?:') . do_commas($re) . ')';
142  }
143  return $re;
144 }
145
146 =head2 C<wc2re>
147
148 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 :
149
150 =over 4
151
152 =item C<'unix'>, C<'win32'>, C<'jokers'>
153
154 For one of those raw rule names, C<wc2re> simply maps to C<wc2re_unix>, C<wc2re_win32> and C<wc2re_jokers> respectively.
155
156 =item C<$^O>
157
158 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.
159
160 =back
161
162 If the type is undefined or not supported, it defaults to C<'unix'>.
163
164      # Wraps to wc2re_jokers ($re eq 'a\\{b\\,c\\}.*').
165      $re = wc2re 'a{b,c}*' => 'jokers';
166
167      # Wraps to wc2re_win32 ($re eq '(?:a\\{b|c\\}.*)')
168      #       or wc2re_unix  ($re eq 'a(?:b|c).*')       depending on $^O.
169      $re = wc2re 'a{b,c}*' => $^O;
170
171 =cut
172
173 my %types = (
174  'jokers'    => \&wc2re_jokers,
175  'unix'      => \&wc2re_unix,
176  map { lc $_ => \&wc2re_win32 } qw/win32 dos os2 MSWin32 cygwin/
177 );
178
179 sub wc2re {
180  my ($wc, $type) = @_;
181  return unless defined $wc;
182  $type = $type ? lc $type : 'unix';
183  $type = 'unix' unless exists $types{$type};
184  return $types{$type}($wc);
185 }
186
187 =head1 EXPORT
188
189 These four functions are exported only on request : C<wc2re>, C<wc2re_unix>, C<wc2re_win32> and C<wc2re_jokers>. The variables are not exported.
190
191 =cut
192
193 use base qw/Exporter/;
194
195 our @EXPORT      = ();
196 our @EXPORT_OK   = ('wc2re', map { 'wc2re_' . $_ } keys %types);
197 our @EXPORT_FAIL = qw/extract do_jokers do_commas do_brackets do_bracketed/; 
198 our %EXPORT_TAGS = ( all => [ @EXPORT_OK ] );
199
200 =head1 DEPENDENCIES
201
202 L<Text::Balanced>, which is bundled with perl since version 5.7.3
203
204 =head1 SEE ALSO
205
206 Some modules provide incomplete alternatives as helper functions :
207
208 L<Net::FTPServer> has a method for that. Only jokers are translated, and escaping won't preserve them.
209
210 L<File::Find::Match::Util> has a C<wildcard> function that compiles a matcher. It only handles C<*>.
211
212 L<Text::Buffer> has the C<convertWildcardToRegex> class method that handles jokers.
213
214 =head1 AUTHOR
215
216 Vincent Pit, C<< <perl at profvince.com> >>
217
218 =head1 BUGS
219
220 Please report any bugs or feature requests to
221 C<bug-regexp-wildcards at rt.cpan.org>, or through the web interface at
222 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Regexp-Wildcards>.
223 I will be notified, and then you'll automatically be notified of progress on
224 your bug as I make changes.
225
226 =head1 SUPPORT
227
228 You can find documentation for this module with the perldoc command.
229
230     perldoc Regexp::Wildcards
231
232 =head1 COPYRIGHT & LICENSE
233
234 Copyright 2007 Vincent Pit, all rights reserved.
235
236 This program is free software; you can redistribute it and/or modify it
237 under the same terms as Perl itself.
238
239 =cut
240
241 sub extract { extract_bracketed shift, '{',  qr/.*?(?:(?<!\\)(?:\\\\)*)(?={)/; }
242
243 sub do_jokers {
244  local $_ = shift;
245  # escape an odd number of \ that doesn't protect a regexp/wildcard special char
246  s/(?<!\\)((?:\\\\)*\\(?:[\w\s]|$))/\\$1/g;
247  # substitute ? preceded by an even number of \
248  my $s = $CaptureSingle ? '(.)' : '.';
249  s/(?<!\\)((?:\\\\)*)\?/$1$s/g;
250  # substitute * preceded by an even number of \
251  $s = $CaptureAny ? (($CaptureAny > 0) ? '(.*)' : '(.*?)')
252                   : '.*';
253  s/(?<!\\)((?:\\\\)*)\*+/$1$s/g;
254  return $_;
255 }
256
257 sub do_commas {
258  local $_ = shift;
259  # substitute , preceded by an even number of \
260  s/(?<!\\)((?:\\\\)*),/$1|/g;
261  return $_;
262 }
263
264 sub do_brackets {
265  my $rest = shift;
266  substr $rest, 0, 1, '';
267  chop $rest;
268  my ($re, $bracket, $prefix) = ('');
269  while (($bracket, $rest, $prefix) = extract $rest and $bracket) {
270   $re .= do_commas($prefix) . do_brackets($bracket);
271  }
272  $re .= do_commas($rest);
273  return ($CaptureBrackets ? '(' : '(?:') . $re . ')';
274 }
275
276 sub do_bracketed {
277  my $rest = shift;
278  my ($re, $bracket, $prefix) = ('');
279  while (($bracket, $rest, $prefix) = extract $rest and $bracket) {
280   $re .= $prefix . do_brackets($bracket);
281  }
282  $re .= $rest;
283  $re =~ s/(?<!\\)((?:\\\\)*[\{\},])/\\$1/g;
284  return $re;
285 }
286
287 1; # End of Regexp::Wildcards