How does regexprep work ? Clarify understanding

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

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일

1 개 추천

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일

0 개 추천

[s(1 : strfind(s, '=')), sprintf(' %g', newvalue)]

이 질문은 마감되었습니다.

질문:

2016년 6월 21일

마감:

2021년 8월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by