regexprep

Replaces text that matches a regular expression.

Category: Language Fundamentals > Data Types

Syntax

newStr = regexprep(str, expr, repl)

Replaces every match of expr in str by repl.

newStr = regexprep(___, option)

Options such as 'once' (first match only) and 'ignorecase'.

Description

Replacement is done in a single left-to-right pass, so the replacement text is not searched again. Group references let you rearrange text: replacing (\w+) (\w+) with $2 $1 swaps two words.

The result keeps the type of the input: a char in gives a char out, a string in gives a string out, and a cell array gives a cell array.

Input arguments

str
Character vector, string, or cell array of them.
expr
Regular expression, or a cell array of expressions applied in order.
repl
Replacement text. $1, $2, ... insert the text captured by each group; $0 inserts the whole match.

Output arguments

newStr
Same type as str, with the replacements made.

Example

regexprep('hello world', '(\w+) (\w+)', '$2 $1')
regexprep('abc', 'B', 'x', 'ignorecase')
regexprep('a  b   c', '\s+', ' ')
regexprep('aaa', 'a', 'b', 'once')
Output
ans = 'world hello'
ans = 'axc'
ans = 'a b c'
ans = 'baa'

See also

regexp regexpi strrep replace regexptranslate