regexp
Matches a regular expression against text and returns positions, matches, tokens or names.
Category: Language Fundamentals > Data Types
Syntax
[start, finish] = regexp(str, expr)
Start and end indices of every match.
out = regexp(str, expr, outkey)
Returns the piece selected by outkey: 'match', 'tokens', 'names', 'split', 'start', 'end', 'tokenExtents'.
[a, b, ...] = regexp(str, expr, key1, key2, ...)
Several outputs in the order requested.
___ = regexp(___, 'once')
Stops after the first match and returns it without the surrounding cell.
___ = regexp(___, 'ignorecase')
Ignores letter case.
Description
regexp scans the text from left to right and finds non-overlapping matches. Without output keys, the outputs come in a fixed order: start, end, token extents, match, tokens, names, split. Naming keys lets you pick only what you need.
If str is a cell array, the outputs are cell arrays with one entry per input element. If nothing matches, 'match' returns an empty cell (or an empty char with 'once').
Input arguments
str- Character vector, string, or cell array of them.
expr- Regular expression. Parentheses create tokens;
(?<name>...)creates a named token. outkey / option- Selector of outputs and options such as
'once','ignorecase','lineanchors'.
Output arguments
start, finish- Row vectors of indices.
match- Cell array of matched text (a single character vector with
'once'). tokens- For each match, a cell array of the text captured by each pair of parentheses.
names- Structure whose fields are the named tokens.
split- Cell array of the text between the matches.
Examples
Matches and tokens
[tok, mat] = regexp('x1y22', '(\w)(\d+)', 'tokens', 'match');
mat
tok{2}
regexp('key=val', '(?<k>\w+)=(?<v>\w+)', 'names')
mat = 1×2 cell
{'x1'} {'y22'}
ans = 1×2 cell
{'y'} {'22'}
ans = struct with fields:
k: 'key'
v: 'val'
Positions and split
[s, e] = regexp('ab12cd345', '\d+')
regexp('a,b;c', '[,;]', 'split')
s = 1×2
3 7
e = 1×2
4 9
ans = 1×3 cell
{'a'} {'b'} {'c'}
Notes
When the expression has no parentheses, MATLAB returns the entire match as a single token; MatLivre currently returns an empty list for 'tokens' in that case, so add a group when you need tokens.