| MATLAB Function Reference | ![]() |
Replace string using regular expression
Syntax
s = regexprep(str,expr,replace,options)
Description
s = regexprep(str,expr,replace)
replaces all occurrences of the regular expression, expr, in string, str, with the string, replace. The new string is returned. If no matches are found regexprep returns str unchanged.
When any of str, expr, or replace are cell arrays of strings, regexprep returns an m-by-n-by-p cell array of strings, where m is the number of strings in str, n is the number of regular expressions in expr, and p is the number of strings in replace.
s = regexprep(str,expr,replace,options)
By default, regexprep replaces all matches, is case sensitive, and does not use tokens. You can use one or more of the following options with regexprep.
Remarks
See Regular Expressions, in the MATLAB documentation, for a listing of all regular expression metacharacters supported by MATLAB.
regexprep does not support international character sets.
Example 1
Perform a case-sensitive replacement on words starting with m and ending with y:
str = 'My flowers may bloom in May'; pat = 'm(\w*)y'; regexprep(str, pat, 'April') ans = My flowers April bloom in May
Replace all words starting with m and ending with y, regardless of case, but maintain the original case in the replacement strings:
Example 2
Replace all variations of the words 'walk up' using the letters following walk as a token.
str = 'I walk up, they walked up, we are walking up, she walks.'; pat = 'walk(\w*) up'; regexprep(str, pat, 'ascend$1', 'tokenize') ans = I ascend, they ascended, we are ascending, she walks.
See Also
regexp, regexpi, strfind, findstr, strmatch, strcmp, strcmpi, strncmp, strncmpi
| regexpi | registerevent (COM) | ![]() |