Bird
Raised Fist0
MATLABdata~10 mins

Regular expressions in MATLAB - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Regular expressions in MATLAB
Input String
↓
Define Pattern
↓
Use regexp Function
↓
Match Found?
No→Return Empty
Yes↓
Return Match Indices or Tokens
↓
Use Matches for Further Processing
The flow shows how MATLAB takes an input string, applies a regular expression pattern using regexp, checks for matches, and returns the results for further use.
Execution Sample
MATLAB
str = 'cat bat rat';
pattern = '\w+at';
matches = regexp(str, pattern, 'match');
disp(matches);
This code finds all words ending with 'at' in the string and displays them.
Execution Table
StepActionInputPatternResultOutput
1Define input string'cat bat rat'
2Define pattern\w+at
3Call regexp'cat bat rat'\w+atFind all matches of words ending with 'at'
4Match 'cat'Match found at indices 1-3matches = {'cat'}
5Match 'bat'Match found at indices 5-7matches = {'cat', 'bat'}
6Match 'rat'Match found at indices 9-11matches = {'cat', 'bat', 'rat'}
7Return matchesDisplay {'cat', 'bat', 'rat'}
💡 All matches found; regexp returns all words ending with 'at' in the string.
Variable Tracker
VariableStartAfter Step 4After Step 5After Step 6Final
str'''cat bat rat''cat bat rat''cat bat rat''cat bat rat'
pattern'''\w+at''\w+at''\w+at''\w+at'
matches{}{'cat'}{'cat', 'bat'}{'cat', 'bat', 'rat'}{'cat', 'bat', 'rat'}
Key Moments - 3 Insights
Why does the pattern use double backslashes like '\\w+at' instead of '\w+at'?
In MATLAB strings, a single backslash is an escape character, so to represent a literal backslash in the pattern, you need to use two backslashes. This is shown in the execution_table where the pattern is '\\w+at'.
What does the 'match' option in regexp do?
The 'match' option tells regexp to return the actual matching substrings instead of their indices. This is why the output in the execution_table shows the matched words like 'cat', 'bat', and 'rat'.
What happens if no matches are found?
If no matches are found, regexp returns an empty cell array. This is shown in the concept_flow where the 'Match Found?' decision leads to returning empty if no matches exist.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 5. What is the content of 'matches' after this step?
A{'cat'}
B{'cat', 'bat'}
C{'bat'}
D{}
💡 Hint
Check the 'Output' column in execution_table row for Step 5.
At which step does the regexp function find the match 'rat'?
AStep 6
BStep 5
CStep 4
DStep 7
💡 Hint
Look at the 'Action' and 'Result' columns in execution_table for the step matching 'rat'.
If the input string was 'dog log fog', what would the 'matches' variable contain after running the same code?
A{'dog', 'log', 'fog'}
B{'og'}
C{}
D{'dog'}
💡 Hint
Refer to the pattern '\\w+at' and check if any words in 'dog log fog' end with 'at'.
Concept Snapshot
MATLAB regexp usage:
- Define input string and pattern (use double backslashes for escapes)
- Call regexp(str, pattern, 'match') to get matching substrings
- Returns cell array of matches or empty if none
- Useful for finding patterns like words ending with 'at'
- Matches can be processed further or displayed
Full Transcript
This visual execution shows how MATLAB uses regular expressions with the regexp function. First, an input string is defined, then a pattern is set using double backslashes to escape special characters. The regexp function is called with the 'match' option to find all substrings matching the pattern. Each match is found step-by-step, updating the matches variable. If no matches are found, an empty cell array is returned. This process helps extract parts of strings that fit a pattern, like words ending with 'at'.

Practice

(1/5)
1. What does the MATLAB function regexp do?
easy
A. Searches for text patterns in strings
B. Replaces text in strings
C. Sorts arrays numerically
D. Calculates the length of a string

Solution

  1. Step 1: Understand the purpose of regexp

    The regexp function in MATLAB is used to find matches of a pattern within text.
  2. Step 2: Compare with other functions

    regexprep replaces text, but regexp only searches for patterns.
  3. Final Answer:

    Searches for text patterns in strings -> Option A
  4. Quick Check:

    regexp = search function [OK]
Hint: Remember: regexp = search, regexprep = replace [OK]
Common Mistakes:
  • Confusing regexp with regexprep
  • Thinking regexp modifies strings
  • Mixing regexp with numeric functions
2. Which of the following is the correct syntax to find all digits in the string 'abc123' using regexp?
easy
A. regexp('abc123', '\\d+')
B. regexp('abc123', '\\w+')
C. regexp('abc123', '\\s+')
D. regexp('abc123', '\\D+')

Solution

  1. Step 1: Identify the pattern for digits

    In regular expressions, \d matches digits, and + means one or more.
  2. Step 2: Check the options

    regexp('abc123', '\\d+') uses \\d+ which correctly matches one or more digits. Others match word characters, spaces, or non-digits.
  3. Final Answer:

    regexp('abc123', '\\d+') -> Option A
  4. Quick Check:

    Digits = \d+ pattern [OK]
Hint: Use \\d+ to match one or more digits [OK]
Common Mistakes:
  • Using \w+ which matches letters and digits
  • Using \s+ which matches spaces
  • Using \D+ which matches non-digits
3. What is the output of the following MATLAB code?
str = 'cat bat rat';
matches = regexp(str, '\\b\w{3}\b', 'match');
disp(matches);
medium
A. ['cat', 'bat']
B. ['catbat', 'rat']
C. [] (empty cell array)
D. ['cat', 'bat', 'rat']

Solution

  1. Step 1: Understand the pattern '\\b\\w{3}\\b'

    The pattern matches word boundaries \\b around exactly 3 word characters \\w{3}.
  2. Step 2: Apply pattern to string

    The string has three 3-letter words: 'cat', 'bat', and 'rat'. All match the pattern.
  3. Final Answer:

    ['cat', 'bat', 'rat'] -> Option D
  4. Quick Check:

    Three 3-letter words matched [OK]
Hint: \b\w{3}\b matches exactly 3-letter words [OK]
Common Mistakes:
  • Ignoring word boundaries and matching partial words
  • Expecting concatenated matches
  • Confusing \w with digits only
4. The following MATLAB code is intended to replace all digits in str with '#' but does not work as expected:
str = 'Room 101';
newStr = regexprep(str, '\d', '#');
disp(newStr);
What is the error and how to fix it?
medium
A. Pattern should be '\\d+' to replace all digits at once
B. No error; code works correctly
C. Pattern should be '\\D' to match digits
D. Use regexp instead of regexprep

Solution

  1. Step 1: Analyze the regexprep usage

    The pattern '\\d' matches any single digit, and regexprep replaces all occurrences by default.
  2. Step 2: Check the output

    Replacing each digit with '#' in 'Room 101' results in 'Room ###', which is expected.
  3. Final Answer:

    No error; code works correctly -> Option B
  4. Quick Check:

    regexprep replaces all matches by default [OK]
Hint: regexprep replaces all matches even with single-digit pattern [OK]
Common Mistakes:
  • Thinking \d replaces only one digit total
  • Using \D which matches non-digits
  • Confusing regexp with regexprep
5. You have a cell array of strings: {'abc123', 'def456', 'ghi789'}. How do you extract only the numeric parts from each string using MATLAB regular expressions?
hard
A. Use regexp(cellArray, '\\d+', 'match')
B. Use regexp(cellArray, '\\w+', 'match')
C. Use regexprep(cellArray, '\\D', '')
D. Use regexprep(cellArray, '\\d+', '')

Solution

  1. Step 1: Understand the goal

    We want to keep only digits, removing all non-digit characters.
  2. Step 2: Choose the correct function and pattern

    regexprep replaces patterns. Using \\D matches non-digits, so replacing them with empty string keeps only digits.
  3. Final Answer:

    Use regexprep(cellArray, '\\D', '') -> Option C
  4. Quick Check:

    Remove non-digits with \D pattern [OK]
Hint: Replace non-digits (\D) with empty string to keep digits [OK]
Common Mistakes:
  • Using regexp with 'match' returns cell arrays, not strings
  • Replacing digits instead of non-digits
  • Using \w+ which matches letters and digits
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard