Effacer les filtres
Effacer les filtres

how to replace 'x\d+' by 'X(...same number as \d+ ...)' such as x45 --> X(45) using regexprep ?

2 vues (au cours des 30 derniers jours)
Hello, I'm searching for replacing, in a text file, strings having 'x' as only non numeric character at the beginning, followed by a number, by 'X(' followed by the same number and followed by ')' using regexprep. For example, I'd want to replace such a line :
' h(1) = -(x21 + x53)/x9 + x183 '
by
' h(1) = -(X(21) + X(53))/X(9) + X(183) '
all the things I tried since yesterday didn't work ... Could you help me ? Thank you
  1 commentaire
genevois pierre
genevois pierre le 26 Oct 2018
Hi again, in fact I had a more general problem : I want to add a constant number to the number that is replaced, for example :
const = 300
line = ' h(1) = -(x21 + x53)/x9 + x183 + b125'
to be replaced by
newline = ' h(1) = -(X(21) + X(53))/X(9) + X(183) + X(425)'
in the last operation, b becomes X and the number is the original one + const ... I tried
for ib = 1:b_varscount
string1 = ['b', num2str(ib)];
string2 = ['X(', num2str(ib+const), ')'];
newline = regexprep(line, string1, string2);
end
but it doesn't work when ib has more than one digit !
thank you for your help.

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 26 Oct 2018
>> str = ' h(1) = -(x21 + x53)/x9 + x183 ';
>> regexprep(str,'x(\d+)','X($1)')
ans = h(1) = -(X(21) + X(53))/X(9) + X(183)

Plus de réponses (0)

Catégories

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

Tags

Produits


Version

R2013a

Community Treasure Hunt

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

Start Hunting!

Translated by