regexp — Match text with regular expressions and return indices, matches, tokens, names, or splits.
regexp(text, pattern) searches character vectors, string arrays, and cell arrays of text and can return start/end indices, matched substrings, capture tokens, token extents, named tokens, or split text. Common MATLAB output and option forms are supported; advanced MATLAB pattern syntax is not yet available.
Syntax
out = regexp(subject, pattern)
out = regexp(subject, pattern, options...)
[start,end_idx,token_extents,match,tokens,names,split] = regexp(subject, pattern, options...)Inputs
subject- Type
Any- Required
- Yes
- Description
- Input text (char/string/string-array/cellstr).
pattern- Type
StringScalar- Required
- Yes
- Description
- Regular-expression pattern.
options- Type
Any- Required
- Variadic
- Description
- Output selectors and regexp options.
Returns
out- Type
Any- Description
- Primary regexp output (depends on options and requested output count).
start- Type
Any- Description
- 1-based match start indices.
end_idx- Type
Any- Description
- 1-based inclusive match end indices.
token_extents- Type
Any- Description
- 1-based start and end indices of capture tokens.
match- Type
Any- Description
- Matched substrings.
tokens- Type
Any- Description
- Capture-group token outputs.
names- Type
Any- Description
- Named capture-group outputs.
split- Type
Any- Description
- Split output around regex matches.
Returned values from regexp depend on how many outputs the caller requests.
Errors
RunMat:regexp:InvalidArgument- When
- Input/options are malformed or unsupported.
- Message
regexp: invalid argument
RunMat:regexp:PatternInvalid- When
- Pattern cannot be compiled as a regular expression.
- Message
regexp: invalid regular expression pattern
RunMat:regexp:Internal- When
- Internal regexp output assembly fails.
- Message
regexp: internal operation failed
Behavior
Single character vectors and string scalars return a numeric row vector of 1-based match start indices by default.
String arrays and cell arrays always produce cell outputs that mirror the input shape, with each cell holding the result for the corresponding element.
'match' returns matched substrings, 'tokens' returns nested cells of capture-group substrings, 'tokenExtents' returns n × 2 double matrices with start/end indices for each token, 'names' returns a cell of scalar structs keyed by named tokens for scalar text (or one struct with 'once'), and 'split' yields the text segments between matches. Array subjects add an outer cell matching the input shape.
'once' stops after the first match (per element), and every requested output honours that limit.
Zero-length matches are omitted by default. Pass 'emptymatch' to include them, or 'noemptymatch' to restore the default. RunMat also accepts its older 'emptymatch','allow'/'remove' form.
'forceCellOutput' forces cell-array containers even for scalar inputs so downstream code can rely on uniform dimensions. MATLAB-compatible 'warnings','on'/'off' flags are accepted but currently informational only.
'matchcase' and 'ignorecase' toggle case sensitivity. Dot (.) matches newlines by default; 'dotexceptnewline' excludes them. 'lineanchors' changes ^ and $ to match line boundaries.
Pattern matching uses Rust's regex engine. MATLAB patterns using lookaround, backreferences, atomic groups, or dynamic expressions are not supported; unsupported patterns report an error.
Integer semantics: numeric match locations are outputs only. Numeric, logical, symbolic, and provider-resident inputs or options are rejected before gather or provider access.
Placement and effects
Matching operates on host text. The builtin has no text GPU kernel or fusion form; numeric and resident text-role inputs reject before provider access. 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
Find all 1-based match positions in a character vector
idx = regexp('abracadabra', 'a')Expected output:
idx =
1 4 6 8 11Return matched substrings using 'match'
matches = regexp('abc123xyz', '\d+', 'match')Expected output:
matches =
1×1 cell array
{'123'}Extract capture tokens
tokens = regexp('2024-03-14', '(\d{4})-(\d{2})-(\d{2})', 'tokens');
year = tokens{1}{1}
month = tokens{1}{2}
day = tokens{1}{3}Expected output:
year =
'2024'
month =
'03'
day =
'14'Split a string array around commas
parts = regexp(["a,b,c"; "1,2,3"], ',', 'split')Expected output:
parts =
2×1 cell array
{1×3 cell}
{1×3 cell}Return only the first match with 'once'
first_idx = regexp('abababa', 'ba', 'once')Expected output:
first_idx =
2Work with named tokens
matches = regexp('X=42; Y=7;', '(?<name>[A-Z])=(?<value>\d+)', 'names');
values = cellfun(@(s) str2double(s.value), matches)Expected output:
values =
42 7Keep zero-length matches with 'emptymatch'
idx = regexp('aba', 'b*', 'emptymatch')Expected output:
idx =
1 2 3 4Using regexp with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how regexp changes the result.
Run a small regexp example, explain the result, then change one input and compare the output.
FAQ
What outputs does regexp return by default?⌄
With a single output argument, regexp returns 1-based match starts. Without output keywords, successive outputs are starts, ends, token extents, matches, tokens, named tokens, and split text. For example, [startIdx, endIdx, extents] = regexp(...) puts token extents in the third output.
How can I request tokens or splits instead of indices?⌄
Specify the desired output types as string flags, for example regexp(str, pat, 'match'), regexp(str, pat, 'tokens'), or regexp(str, pat, 'split'). Multiple flags combine, so regexp(str, pat, 'match', 'tokens') returns both outputs.
Does regexp support case-insensitive matching?⌄
Yes. Use 'ignorecase' (or call regexpi) to enable case-insensitive matching, and 'matchcase' to revert to the default case-sensitive behaviour.
How are string arrays and cell arrays handled?⌄
For string arrays and cell arrays of char vectors, every output is a cell array whose shape matches the input. Each cell contains the result for the corresponding element, which mirrors MATLAB's container semantics.
How do zero-length matches behave?⌄
Zero-length matches are omitted by default. Specify 'emptymatch' to include them; 'noemptymatch' restores the default. RunMat also accepts the older two-argument allow/remove form.
Can I force cell output even for character vectors?⌄
Yes. Pass 'forceCellOutput' to force the outputs into cell arrays, which is useful when writing code that handles both scalar and array inputs uniformly.
Does regexp run on the GPU?⌄
Text matching runs on the host and has no GPU text kernel. Numeric or resident values in text roles are rejected before provider access; supported scalar controls are handled separately.
What happens when I ask for more outputs than I requested via flags?⌄
Without output keywords, up to seven outputs follow the default order: start, end, token extents, match, tokens, names, split. With explicit output keywords, extra requested outputs are padded with numeric zeros.
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 regexp is executed, line by line, in Rust.
- View the source for regexp 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.