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

2 visualizaciones (últimos 30 días)
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 comentario
genevois pierre
genevois pierre el 26 de Oct. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 26 de Oct. de 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)

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2013a

Community Treasure Hunt

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

Start Hunting!

Translated by