Wildcards.pm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. package Regexp::Wildcards;
  2. use strict;
  3. use warnings;
  4. use Carp qw<croak>;
  5. use Scalar::Util qw<blessed>;
  6. use Text::Balanced qw<extract_bracketed>;
  7. =head1 NAME
  8. Regexp::Wildcards - Converts wildcard expressions to Perl regular expressions.
  9. =head1 VERSION
  10. Version 1.05
  11. =cut
  12. use vars qw<$VERSION>;
  13. BEGIN {
  14. $VERSION = '1.05';
  15. }
  16. =head1 SYNOPSIS
  17. use Regexp::Wildcards;
  18. my $rw = Regexp::Wildcards->new(type => 'unix');
  19. my $re;
  20. $re = $rw->convert('a{b?,c}*'); # Do it Unix shell style.
  21. $re = $rw->convert('a?,b*', 'win32'); # Do it Windows shell style.
  22. $re = $rw->convert('*{x,y}?', 'jokers'); # Process the jokers and
  23. # escape the rest.
  24. $re = $rw->convert('%a_c%', 'sql'); # Turn SQL wildcards into
  25. # regexps.
  26. $rw = Regexp::Wildcards->new(
  27. do => [ qw<jokers brackets> ], # Do jokers and brackets.
  28. capture => [ qw<any greedy> ], # Capture *'s greedily.
  29. );
  30. $rw->do(add => 'groups'); # Don't escape groups.
  31. $rw->capture(rem => [ qw<greedy> ]); # Actually we want non-greedy
  32. # matches.
  33. $re = $rw->convert('*a{,(b)?}?c*'); # '(.*?)a(?:|(b).).c(.*?)'
  34. $rw->capture(); # No more captures.
  35. =head1 DESCRIPTION
  36. In many situations, users may want to specify patterns to match but don't need the full power of regexps.
  37. Wildcards make one of those sets of simplified rules.
  38. This module converts wildcard expressions to Perl regular expressions, so that you can use them for matching.
  39. It handles the C<*> and C<?> jokers, as well as Unix bracketed alternatives C<{,}>, but also C<%> and C<_> SQL wildcards.
  40. If required, it can also keep original C<(...)> groups or C<^> and C<$> anchors.
  41. Backspace (C<\>) is used as an escape character.
  42. Typesets that mimic the behaviour of Windows and Unix shells are also provided.
  43. =head1 METHODS
  44. =cut
  45. sub _check_self {
  46. croak 'First argument isn\'t a valid ' . __PACKAGE__ . ' object'
  47. unless blessed $_[0] and $_[0]->isa(__PACKAGE__);
  48. }
  49. my %types = (
  50. jokers => [ qw<jokers> ],
  51. sql => [ qw<sql> ],
  52. commas => [ qw<commas> ],
  53. brackets => [ qw<brackets> ],
  54. unix => [ qw<jokers brackets> ],
  55. win32 => [ qw<jokers commas> ],
  56. );
  57. $types{$_} = $types{win32} for qw<dos os2 MSWin32 cygwin>;
  58. $types{$_} = $types{unix} for qw<linux
  59. darwin machten next
  60. aix irix hpux dgux dynixptx
  61. bsdos freebsd openbsd
  62. svr4 solaris sunos dec_osf
  63. sco_sv unicos unicosmk>;
  64. my %escapes = (
  65. jokers => '?*',
  66. sql => '_%',
  67. commas => ',',
  68. brackets => '{},',
  69. groups => '()',
  70. anchors => '^$',
  71. );
  72. my %captures = (
  73. single => sub { $_[1] ? '(.)' : '.' },
  74. any => sub { $_[1] ? ($_[0]->{greedy} ? '(.*)'
  75. : '(.*?)')
  76. : '.*' },
  77. brackets => sub { $_[1] ? '(' : '(?:'; },
  78. greedy => undef,
  79. );
  80. sub _validate {
  81. my $self = shift;
  82. _check_self $self;
  83. my $valid = shift;
  84. my $old = shift;
  85. $old = { } unless defined $old;
  86. my %opts;
  87. if (@_ <= 1) {
  88. $opts{set} = defined $_[0] ? $_[0] : { };
  89. } elsif (@_ % 2) {
  90. croak 'Arguments must be passed as an unique scalar or as key => value pairs';
  91. } else {
  92. %opts = @_;
  93. }
  94. my %checked;
  95. for (qw<set add rem>) {
  96. my $opt = $opts{$_};
  97. next unless defined $opt;
  98. my $cb = {
  99. '' => sub { +{ ($_[0] => 1) x (exists $valid->{$_[0]}) } },
  100. 'ARRAY' => sub { +{ map { ($_ => 1) x (exists $valid->{$_}) } @{$_[0]} } },
  101. 'HASH' => sub { +{ map { ($_ => $_[0]->{$_}) x (exists $valid->{$_}) }
  102. keys %{$_[0]} } }
  103. }->{ ref $opt };
  104. croak 'Wrong option set' unless $cb;
  105. $checked{$_} = $cb->($opt);
  106. }
  107. my $config = (exists $checked{set}) ? $checked{set} : $old;
  108. $config->{$_} = $checked{add}->{$_} for grep $checked{add}->{$_},
  109. keys %{$checked{add} || {}};
  110. delete $config->{$_} for grep $checked{rem}->{$_},
  111. keys %{$checked{rem} || {}};
  112. $config;
  113. }
  114. sub _do {
  115. my $self = shift;
  116. my $config;
  117. $config->{do} = $self->_validate(\%escapes, $self->{do}, @_);
  118. $config->{escape} = '';
  119. $config->{escape} .= $escapes{$_} for keys %{$config->{do}};
  120. $config->{escape} = quotemeta $config->{escape};
  121. $config;
  122. }
  123. sub do {
  124. my $self = shift;
  125. _check_self $self;
  126. my $config = $self->_do(@_);
  127. $self->{$_} = $config->{$_} for keys %$config;
  128. $self;
  129. }
  130. sub _capture {
  131. my $self = shift;
  132. my $config;
  133. $config->{capture} = $self->_validate(\%captures, $self->{capture}, @_);
  134. $config->{greedy} = delete $config->{capture}->{greedy};
  135. for (keys %captures) {
  136. $config->{'c_' . $_} = $captures{$_}->($config, $config->{capture}->{$_})
  137. if $captures{$_}; # Skip 'greedy'
  138. }
  139. $config;
  140. }
  141. sub capture {
  142. my $self = shift;
  143. _check_self $self;
  144. my $config = $self->_capture(@_);
  145. $self->{$_} = $config->{$_} for keys %$config;
  146. $self;
  147. }
  148. sub _type {
  149. my ($self, $type) = @_;
  150. $type = 'unix' unless defined $type;
  151. croak 'Wrong type' unless exists $types{$type};
  152. my $config = $self->_do($types{$type});
  153. $config->{type} = $type;
  154. $config;
  155. }
  156. sub type {
  157. my $self = shift;
  158. _check_self $self;
  159. my $config = $self->_type(@_);
  160. $self->{$_} = $config->{$_} for keys %$config;
  161. $self;
  162. }
  163. sub new {
  164. my $class = shift;
  165. $class = blessed($class) || $class || __PACKAGE__;
  166. croak 'Optional arguments must be passed as key => value pairs' if @_ % 2;
  167. my %args = @_;
  168. my $self = bless { }, $class;
  169. if (defined $args{do}) {
  170. $self->do($args{do});
  171. } else {
  172. $self->type($args{type});
  173. }
  174. $self->capture($args{capture});
  175. }
  176. =head2 C<new>
  177. my $rw = Regexp::Wildcards->new(do => $what, capture => $capture);
  178. my $rw = Regexp::Wildcards->new(type => $type, capture => $capture);
  179. Constructs a new L<Regexp::Wildcard> object.
  180. C<do> lists all features that should be enabled when converting wildcards to regexps.
  181. Refer to L</do> for details on what can be passed in C<$what>.
  182. The C<type> specifies a predefined set of C<do> features to use.
  183. See L</type> for details on which types are valid.
  184. The C<do> option overrides C<type>.
  185. C<capture> lists which atoms should be capturing.
  186. Refer to L</capture> for more details.
  187. =head2 C<do>
  188. $rw->do($what);
  189. $rw->do(set => $c1);
  190. $rw->do(add => $c2);
  191. $rw->do(rem => $c3);
  192. Specifies the list of metacharacters to convert or to prevent for escaping.
  193. They fit into six classes :
  194. =over 4
  195. =item *
  196. C<'jokers'>
  197. Converts C<?> to C<.> and C<*> to C<.*>.
  198. 'a**\\*b??\\?c' ==> 'a.*\\*b..\\?c'
  199. =item *
  200. C<'sql'>
  201. Converts C<_> to C<.> and C<%> to C<.*>.
  202. 'a%%\\%b__\\_c' ==> 'a.*\\%b..\\_c'
  203. =item *
  204. C<'commas'>
  205. Converts all C<,> to C<|> and puts the complete resulting regular expression inside C<(?: ... )>.
  206. 'a,b{c,d},e' ==> '(?:a|b\\{c|d\\}|e)'
  207. =item *
  208. C<'brackets'>
  209. Converts all matching C<{ ... , ... }> brackets to C<(?: ... | ... )> alternations.
  210. If some brackets are unbalanced, it tries to substitute as many of them as possible, and then escape the remaining unmatched C<{> and C<}>.
  211. Commas outside of any bracket-delimited block are also escaped.
  212. 'a,b{c,d},e' ==> 'a\\,b(?:c|d)\\,e'
  213. '{a\\{b,c}d,e}' ==> '(?:a\\{b|c)d\\,e\\}'
  214. '{a{b,c\\}d,e}' ==> '\\{a\\{b\\,c\\}d\\,e\\}'
  215. =item *
  216. C<'groups'>
  217. Keeps the parenthesis C<( ... )> of the original string without escaping them.
  218. Currently, no check is done to ensure that the parenthesis are matching.
  219. 'a(b(c))d\\(\\)' ==> (no change)
  220. =item *
  221. C<'anchors'>
  222. Prevents the I<beginning-of-line> C<^> and I<end-of-line> C<$> anchors to be escaped.
  223. Since C<[...]> character class are currently escaped, a C<^> will always be interpreted as I<beginning-of-line>.
  224. 'a^b$c' ==> (no change)
  225. =back
  226. Each C<$c> can be any of :
  227. =over 4
  228. =item *
  229. A hash reference, with wanted metacharacter group names (described above) as keys and booleans as values ;
  230. =item *
  231. An array reference containing the list of wanted metacharacter classes ;
  232. =item *
  233. A plain scalar, when only one group is required.
  234. =back
  235. When C<set> is present, the classes given as its value replace the current object options.
  236. Then the C<add> classes are added, and the C<rem> classes removed.
  237. Passing a sole scalar C<$what> is equivalent as passing C<< set => $what >>.
  238. No argument means C<< set => [ ] >>.
  239. $rw->do(set => 'jokers'); # Only translate jokers.
  240. $rw->do('jokers'); # Same.
  241. $rw->do(add => [ qw<sql commas> ]); # Translate also SQL and commas.
  242. $rw->do(rem => 'jokers'); # Specifying both 'sql' and
  243. # 'jokers' is useless.
  244. $rw->do(); # Translate nothing.
  245. The C<do> method returns the L<Regexp::Wildcards> object.
  246. =head2 C<type>
  247. $rw->type($type);
  248. Notifies to convert the metacharacters that corresponds to the predefined type C<$type>.
  249. C<$type> can be any of :
  250. =over 4
  251. =item *
  252. C<'jokers'>, C<'sql'>, C<'commas'>, C<'brackets'>
  253. Singleton types that enable the corresponding C<do> classes.
  254. =item *
  255. C<'unix'>
  256. Covers typical Unix shell globbing features (effectively C<'jokers'> and C<'brackets'>).
  257. =item *
  258. C<$^O> values for common Unix systems
  259. Wrap to C<'unix'> (see L<perlport> for the list).
  260. =item *
  261. C<undef>
  262. Defaults to C<'unix'>.
  263. =item *
  264. C<'win32'>
  265. Covers typical Windows shell globbing features (effectively C<'jokers'> and C<'commas'>).
  266. =item *
  267. C<'dos'>, C<'os2'>, C<'MSWin32'>, C<'cygwin'>
  268. Wrap to C<'win32'>.
  269. =back
  270. In particular, you can usually pass C<$^O> as the C<$type> and get the corresponding shell behaviour.
  271. $rw->type('win32'); # Set type to win32.
  272. $rw->type($^O); # Set type to unix on Unices and win32 on Windows
  273. $rw->type(); # Set type to unix.
  274. The C<type> method returns the L<Regexp::Wildcards> object.
  275. =head2 C<capture>
  276. $rw->capture($captures);
  277. $rw->capture(set => $c1);
  278. $rw->capture(add => $c2);
  279. $rw->capture(rem => $c3);
  280. Specifies the list of atoms to capture.
  281. This method works like L</do>, except that the classes are different :
  282. =over 4
  283. =item *
  284. C<'single'>
  285. Captures all unescaped I<"exactly one"> metacharacters, i.e. C<?> for wildcards or C<_> for SQL.
  286. 'a???b\\??' ==> 'a(.)(.)(.)b\\?(.)'
  287. 'a___b\\__' ==> 'a(.)(.)(.)b\\_(.)'
  288. =item *
  289. C<'any'>
  290. Captures all unescaped I<"any"> metacharacters, i.e. C<*> for wildcards or C<%> for SQL.
  291. 'a***b\\**' ==> 'a(.*)b\\*(.*)'
  292. 'a%%%b\\%%' ==> 'a(.*)b\\%(.*)'
  293. =item *
  294. C<'greedy'>
  295. When used in conjunction with C<'any'>, it makes the C<'any'> captures greedy (by default they are not).
  296. 'a***b\\**' ==> 'a(.*?)b\\*(.*?)'
  297. 'a%%%b\\%%' ==> 'a(.*?)b\\%(.*?)'
  298. =item *
  299. C<'brackets'>
  300. Capture matching C<{ ... , ... }> alternations.
  301. 'a{b\\},\\{c}' ==> 'a(b\\}|\\{c)'
  302. =back
  303. $rw->capture(set => 'single'); # Only capture "exactly one"
  304. # metacharacters.
  305. $rw->capture('single'); # Same.
  306. $rw->capture(add => [ qw<any greedy> ]); # Also greedily capture
  307. # "any" metacharacters.
  308. $rw->capture(rem => 'greedy'); # No more greed please.
  309. $rw->capture(); # Capture nothing.
  310. The C<capture> method returns the L<Regexp::Wildcards> object.
  311. =head2 C<convert>
  312. my $rx = $rw->convert($wc);
  313. my $rx = $rw->convert($wc, $type);
  314. 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.
  315. 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>.
  316. =cut
  317. sub convert {
  318. my ($self, $wc, $type) = @_;
  319. _check_self $self;
  320. my $config = (defined $type) ? $self->_type($type) : $self;
  321. return unless defined $wc;
  322. my $e = $config->{escape};
  323. # Escape :
  324. # - an even number of \ that doesn't protect a regexp/wildcard metachar
  325. # - an odd number of \ that doesn't protect a wildcard metachar
  326. $wc =~ s/
  327. (?<!\\)(
  328. (?:\\\\)*
  329. (?:
  330. [^\w\s\\$e]
  331. |
  332. \\
  333. (?: [^\W$e] | \s | $ )
  334. )
  335. )
  336. /\\$1/gx;
  337. my $do = $config->{do};
  338. $wc = $self->_jokers($wc) if $do->{jokers};
  339. $wc = $self->_sql($wc) if $do->{sql};
  340. if ($do->{brackets}) {
  341. $wc = $self->_bracketed($wc);
  342. } elsif ($do->{commas} and $wc =~ /(?<!\\)(?:\\\\)*,/) {
  343. $wc = $self->{'c_brackets'} . $self->_commas($wc) . ')';
  344. }
  345. $wc
  346. }
  347. =head1 EXPORT
  348. An object module shouldn't export any function, and so does this one.
  349. =head1 DEPENDENCIES
  350. L<Carp> (core module since perl 5), L<Scalar::Util>, L<Text::Balanced> (since 5.7.3).
  351. =head1 CAVEATS
  352. 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).
  353. 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.
  354. =head1 SEE ALSO
  355. L<Text::Glob>.
  356. =head1 AUTHOR
  357. Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
  358. You can contact me by mail or on C<irc.perl.org> (vincent).
  359. =head1 BUGS
  360. 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>.
  361. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
  362. =head1 SUPPORT
  363. You can find documentation for this module with the perldoc command.
  364. perldoc Regexp::Wildcards
  365. Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Regexp-Wildcards>.
  366. =head1 COPYRIGHT & LICENSE
  367. Copyright 2007,2008,2009,2013 Vincent Pit, all rights reserved.
  368. This program is free software; you can redistribute it and/or modify it
  369. under the same terms as Perl itself.
  370. =cut
  371. sub _extract ($) { extract_bracketed $_[0], '{', qr/.*?(?<!\\)(?:\\\\)*(?={)/ }
  372. sub _jokers {
  373. my $self = shift;
  374. local $_ = $_[0];
  375. # substitute ? preceded by an even number of \
  376. my $s = $self->{c_single};
  377. s/(?<!\\)((?:\\\\)*)\?/$1$s/g;
  378. # substitute * preceded by an even number of \
  379. $s = $self->{c_any};
  380. s/(?<!\\)((?:\\\\)*)\*+/$1$s/g;
  381. $_
  382. }
  383. sub _sql {
  384. my $self = shift;
  385. local $_ = $_[0];
  386. # substitute _ preceded by an even number of \
  387. my $s = $self->{c_single};
  388. s/(?<!\\)((?:\\\\)*)_/$1$s/g;
  389. # substitute % preceded by an even number of \
  390. $s = $self->{c_any};
  391. s/(?<!\\)((?:\\\\)*)%+/$1$s/g;
  392. $_
  393. }
  394. sub _commas {
  395. local $_ = $_[1];
  396. # substitute , preceded by an even number of \
  397. s/(?<!\\)((?:\\\\)*),/$1|/g;
  398. $_
  399. }
  400. sub _brackets {
  401. my ($self, $rest) = @_;
  402. substr $rest, 0, 1, '';
  403. chop $rest;
  404. my ($re, $bracket, $prefix) = ('');
  405. while (do { ($bracket, $rest, $prefix) = _extract $rest; $bracket }) {
  406. $re .= $self->_commas($prefix) . $self->_brackets($bracket);
  407. }
  408. $re .= $self->_commas($rest);
  409. $self->{c_brackets} . $re . ')';
  410. }
  411. sub _bracketed {
  412. my ($self, $rest) = @_;
  413. my ($re, $bracket, $prefix) = ('');
  414. while (do { ($bracket, $rest, $prefix) = _extract $rest; $bracket }) {
  415. $re .= $prefix . $self->_brackets($bracket);
  416. }
  417. $re .= $rest;
  418. $re =~ s/(?<!\\)((?:\\\\)*[\{\},])/\\$1/g;
  419. $re;
  420. }
  421. 1; # End of Regexp::Wildcards