How does regexprep work ? Clarify understanding
Informazioni
Questa domanda è chiusa. Riaprila per modificarla o per rispondere.
Mostra commenti meno recenti
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 Commenti
Rodriguez Pham
il 21 Giu 2016
@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.
Risposte (2)
Kelly Kearney
il 21 Giu 2016
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
il 21 Giu 2016
[s(1 : strfind(s, '=')), sprintf(' %g', newvalue)]
Questa domanda è chiusa.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!