Regular Expressions
A regular expression (regex) is a small pattern language for describing text: "one or more digits", "a word followed by an equals sign", "an email-like thing". String Functions showed a first taste of regexp and regexprep. This lesson covers the pattern syntax and every useful output of the three regex functions:
| Function | Purpose |
|---|---|
regexp(str, pat, ...) |
Find matches and return positions, the matched text, groups, names or the pieces between matches |
regexpi(str, pat, ...) |
The same, ignoring upper/lower case |
regexprep(str, pat, rep, ...) |
Replace matches, with $1, $2, … referring to captured groups |
All three work on char arrays, cellstr and (in MATLAB) string arrays, and everything in this lesson runs in both MATLAB and Octave unless marked otherwise.
Pattern syntax
| Pattern | Matches |
|---|---|
. |
Any single character |
\d \w \s |
A digit, a word character (letter, digit, _), a whitespace character |
\D \W \S |
The opposites: not a digit, not a word character, not whitespace |
[abc] [a-z] [^0-9] |
One character from a set, a range, or not in the set |
* + ? |
Zero or more, one or more, zero or one of the previous item |
{n} {n,} {n,m} |
Exactly n, at least n, between n and m repetitions |
*? +? |
Lazy versions: match as few characters as possible |
^ $ |
Start and end of the text |
\< \> |
Start and end of a word |
(...) |
A capturing group (a token) |
(?<name>...) |
A named group |
(?:...) |
A group that doesn't capture |
a|b |
Either a or b |
(?=...) (?<=...) |
Lookahead / lookbehind: "followed by" / "preceded by", without consuming |
\. \( \$ |
A literal special character |
Note: In MATLAB and Octave
\bin a pattern means a backspace character, not a word boundary as in Perl, Python or JavaScript. Use\<and\>for word boundaries.
s = 'cat category concat cat';
disp(regexp(s, 'cat', 'match'))
words = regexp(s, '\<cat\>', 'match');
fprintf('whole word "cat": %d times\n', numel(words));
disp(regexp(s, '\<cat\w*', 'match')){
[1,1] = cat
[1,2] = cat
[1,3] = cat
[1,4] = cat
}
whole word "cat": 2 times
{
[1,1] = cat
[1,2] = category
[1,3] = cat
}
The plain pattern finds cat four times (including inside category and concat), the word-bounded one only twice, and \<cat\w* finds the words that start with "cat".
What regexp can return
By default regexp returns the start index of every match. Option keywords choose other outputs, and when you ask for several, they come back in the order you list them:
| Keyword | Output |
|---|---|
'start' / 'end' |
Index of the first / last character of each match |
'match' |
Cell array of the matched texts |
'tokens' |
Cell array with, for each match, a cell array of the captured groups |
'names' |
Struct (array) whose fields are the named groups |
'split' |
The pieces of text between the matches |
'once' |
Only the first match, returned without the outer cell |
s = 'Room 12, floor 3, wing 205';
starts = regexp(s, '\d+')
[nums, pos] = regexp(s, '\d+', 'match', 'start')
firstNum = regexp(s, '\d+', 'match', 'once')
pieces = regexp(s, ',\s*', 'split')starts =
6 16 24
nums =
{
[1,1] = 12
[1,2] = 3
[1,3] = 205
}
pos =
6 16 24
firstNum = 12
pieces =
{
[1,1] = Room 12
[1,2] = floor 3
[1,3] = wing 205
}
Without 'once', a search that finds nothing returns an empty cell; with 'once' and 'match' it returns an empty char array, so isempty works in both cases.
Tokens: capturing parts of a match
Parentheses mark the parts you want to extract. With 'tokens', every match gives a cell array of its groups, so the result is a cell array of cell arrays:
log = 'Ann scored 31, Bob scored 27, Cy scored 45';
tok = regexp(log, '(\w+) scored (\d+)', 'tokens');
fprintf('%d matches\n', numel(tok));
for k = 1:numel(tok)
fprintf('%-4s -> %d\n', tok{k}{1}, str2double(tok{k}{2}));
end
scores = cellfun(@(t) str2double(t{2}), tok)3 matches
Ann -> 31
Bob -> 27
Cy -> 45
scores =
31 27 45
The captured text is always a char array, so convert numbers with str2double. The cellfun line pulls the second group out of every match into one numeric vector.
Named tokens
Naming the groups with (?<name>...) makes the code self-documenting. The 'names' output is a struct with one field per name; with several matches it is a struct array, one element per match:
line = 'host=db01 port=5432 user=admin';
kv = regexp(line, '(?<key>\w+)=(?<value>\w+)', 'names');
disp(size(kv))
for k = 1:numel(kv)
fprintf('%s: %s\n', kv(k).key, kv(k).value);
end
d = regexp('Due 2025-11-03', '(?<y>\d{4})-(?<m>\d\d)-(?<d>\d\d)', 'names');
fprintf('year %s, month %s, day %s\n', d.y, d.m, d.d); 1 3
host: db01
port: 5432
user: admin
year 2025, month 11, day 03
With no match, 'names' returns a 0x0 struct array that still has the fields, so isempty(d) is the test to use. Structures covers struct arrays in more depth.
Greedy vs lazy
Quantifiers are greedy: they take as much text as they can while the overall match still succeeds. Add ? to make them lazy:
html = '<b>bold</b> and <b>more</b>';
greedy = regexp(html, '<b>.*</b>', 'match')
lazy = regexp(html, '<b>.*?</b>', 'match')
inner = regexp(html, '<b>(.*?)</b>', 'tokens');
fprintf('inner texts: %s, %s\n', inner{1}{1}, inner{2}{1});greedy =
{
[1,1] = <b>bold</b> and <b>more</b>
}
lazy =
{
[1,1] = <b>bold</b>
[1,2] = <b>more</b>
}
inner texts: bold, more
Ignoring case
Use regexpi, pass the 'ignorecase' option, or put (?i) at the start of the pattern:
s = 'Error: disk full. ERROR: fan stopped. error: retry';
disp(numel(regexp(s, 'error', 'match')))
disp(numel(regexpi(s, 'error', 'match')))
disp(numel(regexp(s, 'error', 'match', 'ignorecase')))
disp(regexprep(s, '(?i)error', 'E'))1
3
3
E: disk full. E: fan stopped. E: retry
Replacing with regexprep
regexprep replaces every match. In the replacement text, $1, $2, … insert the groups of the current match, so you can reorder or wrap parts:
disp(regexprep('Hopper, Grace', '(\w+), (\w+)', '$2 $1'))
disp(regexprep('see 3 apples and 12 pears', '(\d+)', '[$1]'))
disp(regexprep('a.b.c', '\.', '/'))
disp(regexprep('a.b.c', '.', '-'))
disp(regexprep('aaa', 'a', 'b', 'once'))
disp(regexprep('trim these spaces', ' {2,}', ' '))
clean = regexprep({'x-1', 'y-22'}, '-\d+', '')Grace Hopper
see [3] apples and [12] pears
a/b/c
-----
baa
trim these spaces
clean =
{
[1,1] = x
[1,2] = y
}
Two classic mistakes are on show here: an unescaped . matches every character (so 'a.b.c' becomes -----), and a replacement normally changes every match unless you pass 'once'. To escape a literal text automatically, use regexptranslate('escape', txt).
MATLAB has two extra replacement features that Octave 11 doesn't support: $0 for the whole match, and dynamic expressions that run MATLAB code on each match:
% MATLAB only
regexprep('cat dog', '\w+', '<$0>')
regexprep('hello big world', '(\w)(\w*)', '${upper($1)}$2')MATLAB output:
ans =
'<cat> <dog>'
ans =
'Hello Big World'The portable way to write the first is to wrap the whole pattern in a group and use $1. For the second, find the positions and change the text yourself:
disp(regexprep('cat dog', '(\w+)', '<$1>'))
s = 'hello big world';
idx = regexp(s, '\<\w');
s(idx) = upper(s(idx));
disp(s)<cat> <dog>
Hello Big World
Validating input
A regex anchored with ^ and $ must match the entire text, which makes it a compact validator. Combine it with 'once' so the result is empty or not:
isCode = @(s) ~isempty(regexp(s, '^[A-Z]{3}-\d{4}