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.
Info
La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.
How does regexprep work ? Clarify understanding
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Stephen23
el 22 de Jun. de 2016
Editada: Stephen23
el 22 de Jun. de 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.
Respuestas (2)
Kelly Kearney
el 21 de Jun. de 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!
0 comentarios
Walter Roberson
el 21 de Jun. de 2016
[s(1 : strfind(s, '=')), sprintf(' %g', newvalue)]
0 comentarios
La pregunta está cerrada.
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!