1 ## Copyright (C) 2008-2012 David Bateman
3 ## This file is part of Octave.
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ## General Public License for more details.
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING. If not, see
17 ## <http://www.gnu.org/licenses/>.
20 ## @deftypefn {Function File} {} regexptranslate (@var{op}, @var{s})
21 ## Translate a string for use in a regular expression. This may
22 ## include either wildcard replacement or special character escaping.
23 ## The behavior is controlled by @var{op} which can take the following
28 ## The wildcard characters @code{.}, @code{*}, and @code{?} are replaced
29 ## with wildcards that are appropriate for a regular expression.
34 ## regexptranslate ("wildcard", "*.m")
40 ## The characters @code{$.?[]}, that have special meaning for regular
41 ## expressions are escaped so that they are treated literally. For example:
45 ## regexptranslate ("escape", "12.5")
51 ## @seealso{regexp, regexpi, regexprep}
54 function y = regexptranslate (op, s)
61 error ("regexptranslate: operation OP must be a string");
65 if (strcmp ("wildcard", op))
66 y = regexprep (regexprep (regexprep (s, '\.', '\.'),
69 elseif (strcmp ("escape", op))
70 y = regexprep (s, '([^\w])', '\$1');
72 error ("regexptranslate: invalid operation OP");
78 %!assert (regexptranslate ("wildcard", "/a*b?c."), "/a.*b.c\\.")
79 %!assert (regexptranslate ("escape", '$.?[abc]'), '\$\.\?\[abc\]')
81 %% Test input validation
82 %!error <Invalid call to regexptranslate> regexptranslate ()
83 %!error <Invalid call to regexptranslate> regexptranslate ("wildcard")
84 %!error <Invalid call to regexptranslate> regexptranslate ("a", "b", "c")
85 %!error <invalid operation> regexptranslate ("foo", "abc")
86 %!error <operation OP must be a string> regexptranslate (10, "abc")