# HG changeset patch # User Rik # Date 1316581260 25200 # Node ID 8a124aeb7ded88988235f7f62e411ff187fed88d # Parent cc1fd6a58151b835cad29b1c7d22639b12a93e55 regexptranslate.m: Correctly escape *all* regular expression special characters. * regexptranslate.m: Correctly escape *all* regular expression special characters. Simplify code and move input validation to start of function. Add new tests. diff --git a/scripts/strings/regexptranslate.m b/scripts/strings/regexptranslate.m --- a/scripts/strings/regexptranslate.m +++ b/scripts/strings/regexptranslate.m @@ -18,14 +18,14 @@ ## -*- texinfo -*- ## @deftypefn {Function File} {} regexptranslate (@var{op}, @var{s}) -## Translate a string for use in a regular expression. This might +## Translate a string for use in a regular expression. This may ## include either wildcard replacement or special character escaping. -## The behavior can be controlled by the @var{op} that can have the +## The behavior is controlled by @var{op} which can take the following ## values ## ## @table @asis ## @item "wildcard" -## The wildcard characters @code{.}, @code{*} and @code{?} are replaced +## The wildcard characters @code{.}, @code{*}, and @code{?} are replaced ## with wildcards that are appropriate for a regular expression. ## For example: ## @@ -57,29 +57,31 @@ print_usage (); endif - if (ischar (op)) - op = tolower (op); - if (strcmp ("wildcard", op)) - y = regexprep (regexprep (regexprep (s, '\.', '\.'), '\*', - '.*'), '\?', '.'); - elseif (strcmp ("escape", op)) - ch = {'\$', '\.', '\?', '\[', '\]'}; - y = s; - for i = 1 : length (ch) - y = regexprep (y, ch{i}, ch{i}); - endfor - else - error ("regexptranslate: unexpected operation"); - endif + if (! ischar (op)) + error ("regexptranslate: operation OP must be a string"); + endif + + op = tolower (op); + if (strcmp ("wildcard", op)) + y = regexprep (regexprep (regexprep (s, '\.', '\.'), + '\*', '.*'), + '\?', '.'); + elseif (strcmp ("escape", op)) + y = regexprep (s, '([^\w])', '\$1'); else - error ("regexptranslate: expecting operation to be a string"); + error ("regexptranslate: invalid operation OP"); endif + endfunction -%!error regexptranslate (); -%!error regexptranslate ("wildcard"); -%!error regexptranslate ("a", "b", "c"); -%!error regexptranslate ("foo", "abc"); -%!error regexptranslate (10, "abc"); + %!assert (regexptranslate ("wildcard", "/a*b?c."), "/a.*b.c\\.") -%!assert (regexptranslate ("escape", '$.?[]'), '\$\.\?\[\]') +%!assert (regexptranslate ("escape", '$.?[abc]'), '\$\.\?\[abc\]') + +%% Test input validation +%!error regexptranslate () +%!error regexptranslate ("wildcard") +%!error regexptranslate ("a", "b", "c") +%!error regexptranslate ("foo", "abc") +%!error regexptranslate (10, "abc") +