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
Questa domanda è chiusa. Riaprila per modificarla o per rispondere.
How does regexprep work ? Clarify understanding
1 visualizzazione (ultimi 30 giorni)
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
Stephen23
il 22 Giu 2016
Modificato: Stephen23
il 22 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!
0 Commenti
Questa domanda è chiusa.
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!