1 package Regexp::Wildcards;
6 use Text::Balanced qw/extract_bracketed/;
10 Regexp::Wildcards - Converts wildcard expressions to Perl regular expressions.
18 our $VERSION = '0.05';
22 use Regexp::Wildcards qw/wc2re/;
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.
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.
35 These variables control if the wildcards jokers and brackets must capture their match. They can be globally set by writing in your program
37 $Regexp::Wildcards::CaptureSingle = 1;
38 # From then, the '?' joker is capturing
40 or can be locally specified via C<local>
43 local $Regexp::Wildcards::CaptureAny = 1;
44 # In this block, the '?' joker is capturing.
47 # Back to the situation from before the block
49 This section describes also how those elements are translated by the L<functions|/FUNCTIONS>.
51 =head2 C<$CaptureSingle>
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.
55 'a???b\\??' is translated to 'a(.)(.)(.)b\\?(.)' if $CaptureSingle is true
56 'a...b\\?.' otherwise (default)
60 our $CaptureSingle = 0;
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<(.*?)>).
66 'a***b\\**' is translated to 'a.*b\\*.*' if $CaptureAny is false (default)
67 'a(.*)b\\*(.*)' if $CaptureAny > 0
68 'a(.*?)b\\*(.*?)' otherwise
74 =head2 C<$CaptureBrackets>
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.
78 'a{b\\},\\{c}' is translated to 'a(b\\}|\\{c)' if $CaptureBrackets is true
79 'a(?:b\\}|\\{c)' otherwise (default)
83 our $CaptureBrackets = 0;
87 =head2 C<wc2re_jokers>
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.
91 # Everything is escaped.
92 print 'ok' if wc2re_jokers('{a{b,c}d,e}') eq '\\{a\\{b\\,c\\}d\\,e\\}';
98 $wc =~ s/(?<!\\)((?:\\\\)*[^\w\s?*\\])/\\$1/g;
99 return do_jokers($wc);
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.
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)';
109 The function handles unbalanced bracket expressions, by escaping everything it can't recognize. For example :
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\\}';
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\\}';
121 return unless defined $re;
122 $re =~ s/(?<!\\)((?:\\\\)*[^\w\s?*\\\{\},])/\\$1/g;
123 return do_bracketed(do_jokers($re));
126 =head2 C<wc2re_win32>
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.
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\\})';
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) . ')';
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 :
152 =item C<'unix'>, C<'win32'>, C<'jokers'>
154 For one of those raw rule names, C<wc2re> simply maps to C<wc2re_unix>, C<wc2re_win32> and C<wc2re_jokers> respectively.
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.
162 If the type is undefined or not supported, it defaults to C<'unix'>.
164 # Wraps to wc2re_jokers ($re eq 'a\\{b\\,c\\}.*').
165 $re = wc2re 'a{b,c}*' => 'jokers';
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;
174 'jokers' => \&wc2re_jokers,
175 'unix' => \&wc2re_unix,
176 map { lc $_ => \&wc2re_win32 } qw/win32 dos os2 MSWin32 cygwin/
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);
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.
193 use base qw/Exporter/;
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 ] );
202 L<Text::Balanced>, which is bundled with perl since version 5.7.3
206 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.
210 Some modules provide incomplete alternatives as helper functions :
212 L<Net::FTPServer> has a method for that. Only jokers are translated, and escaping won't preserve them.
214 L<File::Find::Match::Util> has a C<wildcard> function that compiles a matcher. It only handles C<*>.
216 L<Text::Buffer> has the C<convertWildcardToRegex> class method that handles jokers.
220 Vincent Pit, C<< <perl at profvince.com> >>
224 Please report any bugs or feature requests to
225 C<bug-regexp-wildcards at rt.cpan.org>, or through the web interface at
226 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Regexp-Wildcards>.
227 I will be notified, and then you'll automatically be notified of progress on
228 your bug as I make changes.
232 You can find documentation for this module with the perldoc command.
234 perldoc Regexp::Wildcards
236 =head1 COPYRIGHT & LICENSE
238 Copyright 2007 Vincent Pit, all rights reserved.
240 This program is free software; you can redistribute it and/or modify it
241 under the same terms as Perl itself.
245 sub extract { extract_bracketed shift, '{', qr/.*?(?<!\\)(?:\\\\)*(?={)/; }
249 # escape an odd number of \ that doesn't protect a regexp/wildcard special char
250 s/(?<!\\)((?:\\\\)*\\(?:[\w\s]|$))/\\$1/g;
251 # substitute ? preceded by an even number of \
252 my $s = $CaptureSingle ? '(.)' : '.';
253 s/(?<!\\)((?:\\\\)*)\?/$1$s/g;
254 # substitute * preceded by an even number of \
255 $s = $CaptureAny ? (($CaptureAny > 0) ? '(.*)' : '(.*?)')
257 s/(?<!\\)((?:\\\\)*)\*+/$1$s/g;
263 # substitute , preceded by an even number of \
264 s/(?<!\\)((?:\\\\)*),/$1|/g;
270 substr $rest, 0, 1, '';
272 my ($re, $bracket, $prefix) = ('');
273 while (($bracket, $rest, $prefix) = extract $rest and $bracket) {
274 $re .= do_commas($prefix) . do_brackets($bracket);
276 $re .= do_commas($rest);
277 return ($CaptureBrackets ? '(' : '(?:') . $re . ')';
282 my ($re, $bracket, $prefix) = ('');
283 while (($bracket, $rest, $prefix) = extract $rest and $bracket) {
284 $re .= $prefix . do_brackets($bracket);
287 $re =~ s/(?<!\\)((?:\\\\)*[\{\},])/\\$1/g;
291 1; # End of Regexp::Wildcards