Replace multiple lines using regular expression

조회 수: 5 (최근 30일)
Ravi Rahul Kumar Shah
Ravi Rahul Kumar Shah 2021년 10월 14일
답변: Sameer 2024년 2월 14일
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
Mathieu NOE
Mathieu NOE 2021년 10월 14일
hello
do it in a for loop (one iteration = one line processed)

댓글을 달려면 로그인하십시오.

답변 (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