Replace multiple lines using regular expression

10 次查看(过去 30 天)
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

回答(1 个)

Sameer
Sameer 2024-2-14
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

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by