Replace multiple lines using regular expression

9 views (last 30 days)
How do I replace multiple lines using regular Expression?
strTxt = 'Hello! This is just a text and in new line inputParameter';
inputParameter = magic(5);
strTxt = regexprep(strTxt, 'inputParameter', inputParameter); % it is showing error

Answers (1)

Sameer
Sameer on 14 Feb 2024
Hi Ravi,
From my understanding, you've encountered an issue when trying to replace a substring in a string using regular expressions. Additionally, you're seeking information on how to replace multiple lines.
The error in your code is occurring because regexprep expects the replacement string to be a character array (or string), but inputParameter is a matrix since it's generated by the magic(5) function. MATLAB cannot directly convert a numeric matrix into a string format suitable for inclusion in a text string without explicit formatting.
If you want to include a string representation of the inputParameter matrix in strTxt, you need to convert it to a string first. You can use "mat2str" to convert the matrix into a string representation, and then pass that to regexprep.
Below is the corrected code:
strTxt = 'Hello! This is just a text and in new line inputParameter';
inputParameter = magic(5);
% Convert the matrix to a string representation
inputParameterStr = mat2str(inputParameter);
% Replace 'inputParameter' in the text with its string representation
strTxt = regexprep(strTxt, 'inputParameter', inputParameterStr)
For a multi-line scenario, you can use similar code, as ‘regexprep’ will work regardless of whether the string is single or multi-line. The regular expression 'inputParameter' will match the placeholder text whether it is on the same line or across multiple lines.
Below is an example code:
%Multi-line text
strTxt = sprintf('Hello! This is just a text\nand in new line inputParameter\nwith some more text following it.');
inputParameter = magic(5);
inputParameterStr = mat2str(inputParameter, 5);
strTxt = regexprep(strTxt, 'inputParameter', inputParameterStr)
Hope this helps!
Sameer

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!