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

1 次查看(过去 30 天)
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 个评论
genevois pierre
genevois pierre 2018-10-26
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.

请先登录,再进行评论。

采纳的回答

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

更多回答(0 个)

类别

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

标签

产品


版本

R2013a

Community Treasure Hunt

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

Start Hunting!

Translated by