regexprep — Replace text with regular expressions across char, string, and cell-text inputs.
regexprep(str, pattern, replacement) replaces regular-expression matches in character vectors, string arrays, and cell arrays of text. Common MATLAB container and option forms are supported; advanced MATLAB pattern syntax is not yet available.
Syntax
out = regexprep(subject, pattern, replacement)
out = regexprep(subject, pattern, replacement, options...)Inputs
subject- Type
Any- Required
- Yes
- Description
- Input text (char/string/string-array/cellstr).
pattern- Type
Any- Required
- Yes
- Description
- Pattern text (scalar, sequence, or elementwise list).
replacement- Type
Any- Required
- Yes
- Description
- Replacement text (scalar, sequence, or elementwise list).
options- Type
Any- Required
- Variadic
- Description
- Regex replacement options (case/lineanchors/dotall/once/emptymatch/...).
Returns
out- Type
Any- Description
- Text with replacements applied (preserves scalar/array shape semantics).
Errors
RunMat:regexprep:InvalidArgument- When
- Input/options are malformed, unsupported, or shape-incompatible.
- Message
regexprep: invalid argument
RunMat:regexprep:PatternInvalid- When
- Pattern cannot be compiled as a regular expression.
- Message
regexprep: invalid regular expression pattern
RunMat:regexprep:Internal- When
- Internal regex replacement or output reconstruction fails.
- Message
regexprep: internal operation failed
Behavior
With scalar text inputs, the result is a scalar of the same kind (char inputs stay char, string scalars stay string scalars).
String arrays and cell arrays are processed element-wise and produce containers with matching shapes. When patterns and replacements are provided as arrays of the same size, they are paired element-by-element; otherwise, scalar patterns/replacements broadcast to every element.
Cell or string arrays of patterns apply sequentially: each (pattern, replacement) pair is applied in order to every element.
The 'once' flag limits each element to the first match. Zero-length matches are skipped by default; 'emptymatch' includes them, and 'noemptymatch' restores the default. The older two-argument allow/remove form also works in RunMat.
'ignorecase' and 'matchcase' control case sensitivity. Dot (.) matches newlines by default; 'dotexceptnewline' excludes them. 'lineanchors' enables line-boundary matching for ^ and $.
The Rust regex engine does not support MATLAB lookaround, backreferences, atomic groups, or dynamic expressions. Unsupported patterns report an error.
'preservecase' adjusts the replacement text so the case pattern of the first match (all upper, all lower, or title case) is preserved.
A positive integer scalar option N replaces only the Nth eligible occurrence and accepts every integer class through exact native validation.
Integer values in the subject, pattern, or replacement text roles reject without implicit decimal formatting or provider access.
Placement and effects
Replacement operates on the host and has no GPU regex kernel or fusion form. Native integer text roles reject before gathering; explicit GPU inputs require a RunMat compatibility extension, then gather and undergo normal text validation. It may throw for malformed arguments and options, but does not mutate workspace state or access files, network, randomness, or time.
An unused result is still evaluated and discarded. Ordinary host-text distribution is distinct from distributed-input support for this builtin.
Examples
Replacing vowels in a character vector
clean = regexprep('abracadabra', '[aeiou]', 'X')Expected output:
clean =
'XbrXcXdXbrX'Applying multiple pattern/replacement pairs sequentially
result = regexprep("Color: red", {'Color', 'red'}, {'Shade', 'blue'})Expected output:
result = "Shade: blue"Performing case-insensitive replacements
names = regexprep(["Alpha"; "beta"; "GaMmA"], 'a', '_', 'ignorecase')Expected output:
names =
3×1 string array
"_lph_"
"bet_"
"G_Mm_"Preserving case of the original match
words = regexprep('MATLAB and matlab', 'matlab', 'runmat', 'preservecase')Expected output:
words =
'RUNMAT and runmat'Limiting replacements to the first match with 'once'
out = regexprep("abababa", 'ba', 'XY', 'once')Expected output:
out = "aXYbaba"Using element-wise patterns for a string array
expr = ["foo", "bar"];
pat = ["f", "ar"];
rep = ["F", "AR"];
exact = regexprep(expr, pat, rep)Expected output:
exact = 1×2 string
"Foo" "bAR"Using regexprep with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how regexprep changes the result.
Run a small regexprep example, explain the result, then change one input and compare the output.
FAQ
How are container outputs shaped?⌄
Outputs mirror the input container. Character vectors return character vectors, string arrays return string arrays with the same size, and cell arrays return cell arrays with matching shape.
Can I supply multiple patterns at once?⌄
Yes. Provide pattern and replacement as equally-sized cell or string arrays. Each pair is applied sequentially to every element, mirroring MATLAB's behaviour.
What if my replacement needs capture-group text?⌄
Use $1, $2, … for numbered groups or ${name} for named groups inside the replacement text. These tokens expand to the corresponding captured substrings.
Does regexprep support case-insensitive matching?⌄
Yes. Pass the 'ignorecase' option (or 'matchcase' to revert). You can also request multiline anchors or dot behaviour changes with 'lineanchors', 'dotall', or 'dotExceptNewline'.
What does 'preservecase' do?⌄
When enabled, regexprep inspects the alphabetic characters in the matched text. If they are all uppercase, lowercase, or title-cased, the replacement text is adjusted to match that style.
Does regexprep execute on the GPU?⌄
No GPU regex kernel is used. Explicit GPU inputs require the RunMat fallback extension; accepted values gather for host replacement and outputs remain host text. Integer text inputs reject rather than being formatted implicitly.
Related Strings functions
Text Analytics
addDependencyDetails · addEntityDetails · addLemmaDetails · addPartOfSpeechDetails · addSentenceDetails · addTypeDetails · bagOfNgrams · bagOfWords · cosineSimilarity · doc2sequence · encode · extractFileText · extractHTMLText · fastTextWordEmbedding · findElement · getAttribute · htmlTree · ind2word · isVocabularyWord · normalizeWords · readWordEmbedding · removeLongWords · removeShortWords · removeStopWords · removeWords · stopWords · tokenDetails · tokenizedDocument · trainWordEmbedding · vaderSentimentScores · vec2word · word2ind · word2vec · wordEncoding · writeWordEmbedding
Transform
append · deblank · erase · eraseBetween · erasePunctuation · eraseURLs · extractAfter · extractBefore · extractBetween · insertAfter · insertBefore · join · lower · pad · replace · replaceBetween · reverse · split · splitlines · strcat · strip · strjoin · strjust · strrep · strsplit · strtrim · upper
Core
blanks · char · compose · convertCharsToStrings · convertContainedStringsToChars · convertStringsToChars · genvarname · int2str · isletter · isspace · isStringScalar · isstrprop · mat2str · native2unicode · newline · num2str · sprintf · sscanf · str2double · str2num · strcmp · strcmpi · string · string.empty · strings · strlength · strncmp · strncmpi · strtok · unicode2native
Search
contains · endsWith · matches · startsWith · strfind
Pattern
digitsPattern · lettersPattern · pattern · regexpPattern · textBoundary · wildcardPattern
Source you can read
Every RunMat function's source is public. Read exactly how regexprep is executed, line by line, in Rust.
- View the source for regexprep in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.