Challenge - 5 Problems
Regex Master in MATLAB
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of regexpi with case-insensitive matching
What is the output of the following MATLAB code?
str = 'Matlab is fun';
expr = 'MAT';
idx = regexpi(str, expr);
disp(idx);
MATLAB
str = 'Matlab is fun'; expr = 'MAT'; idx = regexpi(str, expr); disp(idx);
Attempts:
2 left
💡 Hint
regexpi is case-insensitive and returns start indices of matches.
✗ Incorrect
The expression 'MAT' matches 'Mat' at the start of the string ignoring case, so the index is 1.
❓ Predict Output
intermediate2:00remaining
Using regexp to extract tokens
What does the following MATLAB code output?
str = 'abc123def456';
tokens = regexp(str, '\\d+', 'match');
disp(tokens);
MATLAB
str = 'abc123def456'; tokens = regexp(str, '\d+', 'match'); disp(tokens);
Attempts:
2 left
💡 Hint
The pattern '\d+' matches one or more digits.
✗ Incorrect
regexp with 'match' returns all substrings matching the pattern '\d+', which are '123' and '456'.
❓ Predict Output
advanced2:00remaining
Output of regexprep with backreference
What is the output of this MATLAB code?
str = 'cat bat rat';
newStr = regexprep(str, '(\w+)at', '$1ot');
disp(newStr);
MATLAB
str = 'cat bat rat'; newStr = regexprep(str, '(\w+)at', '$1ot'); disp(newStr);
Attempts:
2 left
💡 Hint
Backreference $1 refers to the first captured group.
✗ Incorrect
The pattern captures the first letter before 'at' and replaces 'at' with 'ot', changing 'cat' to 'cot', 'bat' to 'bot', and 'rat' to 'rot'.
❓ Predict Output
advanced2:00remaining
Error type from invalid regex pattern
What error does this MATLAB code produce?
str = 'hello';
expr = '(hello';
matches = regexp(str, expr);
MATLAB
str = 'hello'; expr = '(hello'; matches = regexp(str, expr);
Attempts:
2 left
💡 Hint
Check if the parentheses in the pattern are balanced.
✗ Incorrect
The pattern '(hello' has an opening parenthesis without a closing one, causing an unbalanced parenthesis error.
🧠 Conceptual
expert3:00remaining
Number of matches found by regexpi with overlapping patterns
Consider the MATLAB code below:
What is the value of
str = 'aaaa';
expr = 'aa';
matches = regexpi(str, expr);
numMatches = length(matches);
What is the value of
numMatches after running this code?MATLAB
str = 'aaaa'; expr = 'aa'; matches = regexpi(str, expr); numMatches = length(matches);
Attempts:
2 left
💡 Hint
regexpi does not find overlapping matches by default.
✗ Incorrect
regexpi finds 'aa' starting at positions 1 and 3, but not overlapping at position 2, so total matches are 2.