Info

此问题已关闭。 请重新打开它进行编辑或回答。

How does regexprep work ? Clarify understanding

1 次查看(过去 30 天)
I want to clarify my understanding of how this works. So lets say I have s = 'dragon(bird).claw_eye = 0.465783;' and I want to replace this to something similar but different value so that s = 'dragon(bird).claw_eye = 1.0;'
This is my current set up:
s = 'dragon(bird).claw_eye = 0.465783;'
pattern = sprintf( '%s\\s*=\\s*[^;]+;', [dragon(bird).claw_eye]);
replacement = sprintf( '%s = %g;', [dragon(bird).claw_eye], 1.0);
s = regexprep(s,pattern,replacement);
Please help
  2 个评论
Rodriguez Pham
Rodriguez Pham 2016-6-21
It probably has to do with the pattern set up. I've read the help summary but im still confused about what I should make as the pattern.
Stephen23
Stephen23 2016-6-22
编辑:Stephen23 2016-6-22
@Rodriguez Pham: what are you going to do with the string?
If you are going to eval it, then this would be one of the slowest and most complicated way to perform what could be a very simple operation. Consider learning faster and more reliable ways to write code. We would happy to help you with this.

回答(2 个)

Kelly Kearney
Kelly Kearney 2016-6-21
I think you're trying to make your pattern more complicated than necessary... building a regular expression via sprintf is rarely necessary. First, if you already have the exact before and after strings, it's probably easier to just use strrep vs regexrep:
x = 0.465783; % your dragon(bird).claw_eye value
s = 'dragon(bird).claw_eye = 0.465783;';
strrep(s, num2str(x, '%g'), '1.0')
ans =
dragon(bird).claw_eye = 1.0;
If you don't always know the exact number you need to replace, I'd suggest defining a regexp pattern that looks for any number following an equals sign (you don't need to worry about what the string looks like prior to that):
regexprep(s, '(?<=\s*=\s*)[\d\.]*', '1.0')
ans =
dragon(bird).claw_eye = 1.0;
That said, this whole setup looks like the sort of thing you might be feeding into an eval command, or some other similar coding structure. If you're doing that, don't!

Walter Roberson
Walter Roberson 2016-6-21
[s(1 : strfind(s, '=')), sprintf(' %g', newvalue)]

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by