## Copyright (C) 2006 Bill Denney ## ## This file is part of Octave. ## ## Octave is free software; you can redistribute it and/or modify it ## under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2, or (at your option) ## any later version. ## ## Octave is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Octave; see the file COPYING. If not, write to the Free ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301, USA. ## -*- texinfo -*- ## @deftypefn {Function File} @var{string} = regexprep(@var{string}, @var{regex}, @var{repstr}, @var{options}) ## Replace occurances of @var{repre} in string with @var{repstr}. ## ## @var{options} may be one or more of ## @table @samp ## @item N ## Replace the Nth match of the regexp ## ## @item once ## Replace only the first occurance of the regexp in the result. (The ## same as @var{N} = 1.) ## ## @item warnings ## This option is ignored, but it does not give an error. ## @end table ## @seealso{regexp} ## @end deftypefn function string = regexprep(string, repre, repstr, varargin) ## Parse input arguements n = -1; for i = 1:length(varargin) if isnumeric(varargin{i}) n = assignn(n, varargin{i}); elseif strcmpi(varargin{i}, "once") n = assignn(n, 1); elseif strcmpi(varargin{i}, "warnings") ## for compatability else ## I could do more type checking here, but it will just throw an ## error for things like cells or other types, and that's OK by ## me. error("regexprep: Unrecognised option '%s'", varargin{i}); endif endfor [st, en] = regexp(string, repre); if (n > 0) if (length(st) >= n) st = st(n); else warning("regexprep: fewer matches than N, original string returned"); st = []; endif endif for i = length(st):-1:1 string = [string(1:st(i)-1) repstr string(en(i)+1:length(string))]; endfor endfunction function n = assignn(n, newn) if (newn < 0) warning("regexprep: negative value for N given; all matches will be replaced"); endif if (n < 0) n = newn; else warning("regexprep: conflicting options given for N"); endif endfunction