0
0
MATLABdata~5 mins

Regular expressions in MATLAB

Choose your learning style9 modes available
Introduction

Regular expressions help you find patterns in text. They make searching and changing text easier and faster.

You want to check if a phone number is in the right format.
You need to find all email addresses in a document.
You want to replace all dates written as 'dd-mm-yyyy' with 'yyyy/mm/dd'.
You want to split a sentence into words based on spaces and punctuation.
Syntax
MATLAB
matches = regexp(str, expression)
matches = regexp(str, expression, 'match')
startIndex = regexp(str, expression, 'start')
newStr = regexprep(str, expression, replaceStr)

regexp finds patterns in text.

regexprep replaces parts of text matching a pattern.

Examples
This finds the phone number pattern in the string.
MATLAB
str = 'My phone is 123-456-7890.';
matches = regexp(str, '\d{3}-\d{3}-\d{4}', 'match');
This finds all email addresses in the string.
MATLAB
str = 'Emails: a@example.com, b@test.org';
matches = regexp(str, '[\w\.]+@[\w\.]+', 'match');
This changes date format from dd-mm-yyyy to yyyy/mm/dd.
MATLAB
str = 'Date: 31-12-2023';
newStr = regexprep(str, '(\d{2})-(\d{2})-(\d{4})', '$3/$2/$1');
Sample Program

This program finds and prints all email addresses in the given string.

MATLAB
str = 'Contact: john.doe@example.com or jane_smith@test.net';
pattern = '[\w\.]+@[\w\.]+\.[a-z]{2,4}';
matches = regexp(str, pattern, 'match');
for i = 1:length(matches)
    fprintf('Found email: %s\n', matches{i});
end
OutputSuccess
Important Notes

Use double backslashes (\\) in MATLAB strings to write a single backslash in the pattern.

Regular expressions are case sensitive by default.

Use 'match' option with regexp to get the actual matching text.

Summary

Regular expressions help find and change text patterns easily.

Use regexp to search and regexprep to replace text.

Patterns use special symbols like \d for digits and + for one or more.