Effacer les filtres
Effacer les filtres

Replace multiple lines using regular expression

5 vues (au cours des 30 derniers jours)
Ravi Rahul Kumar Shah
Ravi Rahul Kumar Shah le 14 Oct 2021
Réponse apportée : Sameer le 14 Fév 2024
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 commentaire
Mathieu NOE
Mathieu NOE le 14 Oct 2021
hello
do it in a for loop (one iteration = one line processed)

Connectez-vous pour commenter.

Réponses (1)

Sameer
Sameer le 14 Fév 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

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by