TExcelTAD
Home › MATLAB / Octave › Regular Expressions

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 \b in a pattern means a backspace character, not a word boundary as in Perl, Python or JavaScript. Use \< and \> for word boundaries.

matlab · try it yourself
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
matlab · try it yourself
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:

matlab · try it yourself
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:

matlab · try it yourself
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:

matlab · try it yourself
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:

matlab · try it yourself
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:

matlab · try it yourself
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
% MATLAB only
regexprep('cat dog', '\w+', '<$0>')
regexprep('hello big world', '(\w)(\w*)', '${upper($1)}$2')

MATLAB output:

text
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:

matlab · try it 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:

matlab · try it yourself
isCode = @(s) ~isempty(regexp(s, '^[A-Z]{3}-\d{4}
  

, 'once'));
tests = {'ABC-1234', 'abc-1234', 'ABCD-123', 'XYZ-0042'};
for k = 1:numel(tests)
    fprintf('%-9s %d\n', tests{k}, isCode(tests{k}));
end
emails = {'ann@example.com', 'not an email', 'bob@mail.org'};
ok = ~cellfun(@isempty, regexp(emails, '^[\w.]+@\w+\.\w+
  

, 'once'))
ABC-1234  1
abc-1234  0
ABCD-123  0
XYZ-0042  1
ok =

  1  0  1

The email pattern is deliberately simple; real email validation is far messier and is best left to a dedicated library or a confirmation message.

Lookaround

Lookahead (?=...) and lookbehind (?<=...) check what surrounds a match without including it. They are useful for picking out numbers that follow a currency sign or come before a unit:

matlab · try it yourself
s = 'Coffee $3.50, cake $4.25, 2 kg sugar';
prices = str2double(regexp(s, '(?<=\$)\d+\.\d+', 'match'))
kg = regexp(s, '\d+(?= kg)', 'match')
prices =

   3.5000   4.2500

kg =
{
  [1,1] = 2
}

A small log parser

Putting it together: parse log lines into a struct array, then summarise them:

matlab · try it yourself
lines = {'10:02 WARN disk 81%', '10:05 INFO backup ok', ...
         '10:09 WARN disk 93%', '10:15 ERROR fan stopped'};
pat = '^(?<time>\d\d:\d\d) (?<level>[A-Z]+) (?<msg>.*)
  

;
recs = regexp(lines, pat, 'names', 'once');
recs = [recs{:}];
levels = {recs.level};
fprintf('%d warnings, %d errors\n', sum(strcmp(levels, 'WARN')), sum(strcmp(levels, 'ERROR')));
for r = recs(~strcmp(levels, 'INFO'))
    fprintf('%s  %-5s %s\n', r.time, r.level, r.msg);
end
2 warnings, 1 errors
10:02  WARN  disk 81%
10:09  WARN  disk 93%
10:15  ERROR fan stopped

Called on a cell array, regexp returns one result per text in a cell, and [recs{:}] concatenates the scalar structs into a struct array. Looping with for r = structArray visits one element at a time.

Learn more: String Arrays, String Functions and the Regex course for the pattern language itself.

Test yourself

Which pattern matches the word cat but not the cat inside category?

  1. '\<cat\>'
  2. '\bcat\b'
  3. 'cat+'
  4. '^cat'

What does regexp('a1b22', '\d+', 'match') return?

  1. {'1', '22'}
  2. [2 4]
  3. '122'
  4. {'a', 'b'}

What is regexprep('Smith, Jo', '(\w+), (\w+)', '$2 $1')?

  1. 'Jo Smith'
  2. 'Smith Jo'
  3. '$2 $1'
  4. 'Smith, Jo'