Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
regexprep is MATLAB’s function for replacing text that matches a regular expression. The call newStr = regexprep(str,expression,replace) returns str with every match of expression replaced by replace; if nothing matches, newStr is identical to str. Options such as 'once', 'ignorecase' and 'preservecase' go after the third argument, and the replacement text can reuse parts of the match through tokens such as $1. This guide is organised around the decisions that cause most errors: which option to pass, which replacement operator to use, and what happens to cell and string arrays.
What regexprep is used for in research
Researchers and analysts commonly use regexprep to clean text before analysis: normalising identifiers in exported spreadsheets, stripping markup from instrument logs, reformatting file names, or standardising labels in survey responses. Because it accepts a cell array or string array as input, one call can clean a whole column of text. For a plain, fixed-text substitution the MathWorks reference lists strrep and replace among the related functions; regexprep is the one to reach for when the text to match is described by a pattern rather than spelled out. The matching side of the same engine is regexp, and the MathWorks page on regular expressions in MATLAB documents the shared pattern syntax.
If you only need to test whether two pieces of text are equal, see our guide to MATLAB strcmp; if you are cleaning text in R instead, the stringr cheat sheet covers the equivalent replacement functions there.
How to install or access it
regexprep is a MATLAB function documented in the official MathWorks help centre at mathworks.com/help/matlab/ref/regexprep.html. Its version history in that documentation shows it was introduced before R2006a, so any current MATLAB release has it. Get MATLAB and its documentation from MathWorks only; the online help also lists the syntax for older releases. The reference page notes support for tall arrays and for thread-based environments. In the MATLAB Command Window, doc regexprep opens the same reference locally.
Step-by-step: replace text with a pattern
The steps below follow the syntax and worked examples in the MathWorks reference page (read 2026-11-12).
- Store the text. Put the input in a character vector, string scalar, cell array or string array, for example
str = 'My flowers may bloom in May'; - Write the pattern. Parentheses create tokens you can reuse. For example
expression = 'M(\w+)y';matches a capital M, then one or more word characters, then y, and captures the middle as token 1. - Write the replacement. This is plain text, optionally with operators such as
$1. For examplereplace = 'April'; - Call the function.
newStr = regexprep(str,expression,replace)gives'My flowers may bloom in April'. In the MathWorks example the pattern matches “May” at the end of the sentence, and that word is replaced. - Add options if needed. Append option strings after the replacement:
regexprep(str,expression,replace,'once'). Options are described in the table below.
Reusing a token in the replacement
The documentation example regexprep('I walk up, they walked up, we are walking up.','walk(\w*) up','ascend$1') returns 'I ascend, they ascended, we are ascending.' The text matched by (\w*) (empty, “ed”, “ing”) is carried into the replacement by $1.
Running MATLAB code inside the replacement
The ${cmd} operator inserts the output of a MATLAB command, with $0 standing for the current match. The documentation capitalises the start of each sentence with regexprep('here are two sentences. neither is capitalized.','(^|\.)\s*.','${upper($0)}'), which returns 'Here are two sentences. Neither is capitalized.'
Processing a cell array
When str is a cell array or string array, the result has the same dimensions, so a whole list of labels is cleaned in one call. The documentation example uses expression = '(.)\1' and replace = '--' on a four-line poem stored as a cell array: every doubled letter is replaced, giving results such as “Whose w–ds” and “vi–age”. When expression or replace is itself a cell array or string array but str is a character vector or string scalar, the output keeps the type of str and each expression is applied in turn to the previous result.
Replacement operators
The following operators are documented for the replace argument.
| Operator | Inserts |
|---|---|
$& or $0 |
The entire match |
$` |
The part of str before the match |
$' |
The part of str after the match (write $'' for a literal $') |
$N |
The Nth token |
$<name> |
The named token name |
${cmd} |
The output of the MATLAB command cmd |
\n, \t, \a, \b, \f, \r, \v, \char |
Newline, tab, and the other listed escape characters; \char inserts the character literally |
Options and the one-per-set rule
You can pass several options in any order, but the documentation allows at most one option from each set below. The default in each set applies if you do not choose.
| Set | Choices (default first) | Effect |
|---|---|---|
| How many matches | 'all', 'once', or a number N |
Replace every match, only the first, or only the Nth match |
| Warnings | 'nowarnings', 'warnings' |
Suppress or display warnings |
| Case | 'matchcase', 'ignorecase' |
Case-sensitive or case-insensitive matching |
| Case of replacement | 'preservecase' |
Ignores case when matching; the replacement takes the case pattern of the matched text (all lower stays lower, all upper stays upper, capitalised stays capitalised, anything else becomes lowercase) |
| Empty matches | 'noemptymatch', 'emptymatch' |
Ignore or replace zero-length matches |
| Dot | 'dotall', 'dotexceptnewline' |
Whether . matches a newline |
| Anchors | 'stringanchors', 'lineanchors' |
Whether ^ and $ match at string or line boundaries |
| Spacing | 'literalspacing', 'freespacing' |
Treat whitespace in the pattern literally, or ignore it (then use \ and \# for a literal space or hash) |
Output and how to read it
The output newStr has the same type as str. A character vector or string scalar input gives the same type back, even if expression and replace are cell or string arrays; a cell array or string array input gives an output of the same size. If no match is found, the output equals the input, with no error, which is the quickest way to spot a pattern that is not matching.
Two documented examples show how options change the output. With 'preservecase', regexprep('My flowers may bloom in May','M(\w+)y','April','preservecase') returns 'My flowers april bloom in April': “may” is matched ignoring case and, being all lowercase, is replaced by lowercase “april”. With 'emptymatch', regexprep('abc','^','__','emptymatch') returns '__abc'; without the option, the zero-length match at the start of the string is ignored.
Troubleshooting
Nothing was replaced
Matching is case-sensitive by default in both regexp and regexprep. Add 'ignorecase' if the capitalisation varies. Zero-length patterns such as ^ also need 'emptymatch'.
The match is longer than expected
Quantifiers are greedy by default. Add ? to make one lazy: the documentation’s example pattern '</?t.*?>' stops at the first closing angle bracket instead of the last. A + after a quantifier makes it possessive.
The wrong token number
For nested parentheses, MathWorks states: “If an expression has nested parentheses, MATLAB captures tokens that correspond to the outermost set of parentheses.” Use (?:expr) for grouping without capturing, or named tokens (?<name>expr) referenced as $<name>.
A literal dollar-apostrophe disappears
In replace, $' is an operator. Write $'' to get the literal characters.
Only part of a pattern should match
Lookaround is supported: (?=expr), (?!expr), (?<=expr), (?<!expr). The MathWorks regular-expressions page notes that a lookahead placed before an expression acts as a logical AND, so (?=[a-z])[^aeiou] matches consonants. Inline flags such as (?i), (?s), (?m) and (?x) can also set modes inside the pattern.
Several replacements at once
One replace with a cell array of expressions applies the same replacement to all. A cell array of replacements with one expression makes that many attempts. Two cell arrays must be the same length and are paired element by element. Each expression is applied to the result of the previous one, so order matters.
Free alternatives
The same task exists in free tools. The syntax differs mainly in how the replacement refers to captured text and how options are passed. The data table below compares the option and token syntax in MATLAB, GNU Octave and Python’s re.sub; the table here shows one documented call from each.
| Tool | Function and signature | Documented example |
|---|---|---|
| MATLAB | regexprep(str,expression,replace,options) |
'M(\w+)y' with 'April' on 'My flowers may bloom in May' |
| GNU Octave | regexprep(string, pat, repstr, opt1, ...) |
regexprep("Bill Dunn", '(\w+) (\w+)', '$2, $1') returns "Dunn, Bill" |
| Python | re.sub(pattern, repl, string, count=0, flags=0) |
re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE) returns 'Baked Beans & Spam' |
Octave’s documentation says its regexp implementation is based on the Perl Compatible Regular Expressions library and that regexprep takes the same options as regexp, plus once; the warnings option is accepted for compatibility but ignored. In Python, a string repl processes backslash escapes and backreferences, and repl may also be a function that receives each match. Check any pattern you port, since each tool documents its own regular-expression syntax.
For other everyday MATLAB functions, see MATLAB median, ismember in MATLAB and MATLAB meshgrid, or browse the research tools hub.
FAQ
What does regexprep do in MATLAB?
It replaces text that matches a regular expression with the text you supply, returning the modified text in the same type as the input. If no match is found the input is returned unchanged.
How do I replace only the first match?
Pass 'once' as an option. Pass a number N to replace only the Nth match.
How do I make regexprep case-insensitive?
Pass 'ignorecase', or use 'preservecase' if the replacement should follow the capitalisation of the matched text.
How do I reuse part of the match in the replacement?
Wrap that part of the pattern in parentheses and refer to it as $1, $2 and so on, or name it with (?<name>expr) and use $<name>.
Can regexprep process a cell array?
Yes. A cell array or string array input produces an output with the same dimensions.
Sources
- MathWorks, regexprep (MATLAB documentation), read 2026-11-12.
- MathWorks, Regular Expressions (MATLAB documentation), read 2026-11-12.
- GNU Octave documentation, Searching and Replacing in Strings, read 2026-11-12.
- Python documentation, re: Regular expression operations, read 2026-11-12.
Data: Replace-by-pattern options and token syntax: MATLAB regexprep, GNU Octave regexprep and Python re.sub
Compares how three documented tools express common regexprep tasks (replace only some matches, ignore case, reuse a captured group, reuse the whole match, compute the replacement). Compiled from the official MathWorks, GNU Octave and Python documentation pages; a cell reads 'Not documented in the page read' where the page read does not state the feature.
| Task | MATLAB regexprep | GNU Octave regexprep | Python re.sub |
|---|---|---|---|
| Replace only the first match | 'once' option | 'once' option | count=1 |
| Replace only the first N matches | Numeric option N | Not documented in the page read | count=N |
| Ignore case when matching | 'ignorecase' option | 'ignorecase' option (as for regexp) | flags=re.IGNORECASE or inline (?i) |
| Insert the Nth captured group | $N in replace | $i in repstr | \N or \g in repl |
| Insert the whole match | $0 or $& in replace | Not documented in the page read | \g in repl |
| Insert a named group | $ in replace | Not documented in the page read | \g in repl |
| Compute the replacement with code | ${cmd} in replace | Not documented in the page read | repl as a function receiving a Match object |
Sources
- MathWorks: regexprep (accessed 2026-11-12)
- GNU Octave: Searching and Replacing in Strings (accessed 2026-11-12)
- Python: re - Regular expression operations (accessed 2026-11-12)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







