Bird
0
0

The following MATLAB code is intended to replace all digits in str with '#' but does not work as expected:

medium📝 Debug Q14 of 15
MATLAB - String Handling
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?
APattern should be '\\d+' to replace all digits at once
BNo error; code works correctly
CPattern should be '\\D' to match digits
DUse regexp instead of regexprep
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More MATLAB Quizzes