How to replace string that perfectly matchs the string?

조회 수: 1 (최근 30일)
Erivelton Gualter
Erivelton Gualter 2020년 4월 22일
댓글: Ameer Hamza 2020년 4월 23일
The title might be a litle vague, but I am looking to replace a string on a text by another string using regexprep or any other function. However, all my attempts have failed.
For the following example:
str = 'a = 1; b = 2; var1 = a + b; bar1 = a*b;'
If I use regexprep
>> regexprep(str, 'a', 'v1')
ans =
'v1 = 1; b = 2; vv1r1 = v1 + b; bv1r1 = v1*b;'
However, I was looking for:
'v1 = 1; b = 2; var1 = v1 + b; bar1 = v1*b;'
I have been reading the documentation and try differents aproachs, but I could not figure out this. I have a feeling that regexprep can easily solve this problem. I just need to trick this a bit.
Tks in advance, I will keep digging on.

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 4월 22일
편집: Ameer Hamza 2020년 4월 22일
str = 'a = 1; b = 2; var1 = a + b; bar1 = a*b;';
new_str = regexprep(str, 'a\>', 'v1');
Result:
new_str =
'v1 = 1; b = 2; var1 = v1 + b; bar1 = v1*b;'
  댓글 수: 3
Erivelton Gualter
Erivelton Gualter 2020년 4월 22일
Hi Ameer,
Actualy it did not work quite well. Check the following example:
str = 'An = B(m+1:n,m+1:n); C = D(1:m,mn+1:n);'
It is returning the following:
regexprep(str, 'n\>', 'X')
ans =
'AX = B(m+1:X,m+1:X); C = D(1:m,mX+1:X);'
However, the output should be:
ans =
'An = B(m+1:X,m+1:X); C = D(1:m,mn+1:X);'
Ameer Hamza
Ameer Hamza 2020년 4월 23일
For this specific case
str = 'An = B(m+1:n,m+1:n); C = D(1:m,mn+1:n);';
new_str = regexprep(str, '([^\w])n\>', '$1X')
Result:
new_str =
'An = B(m+1:X,m+1:X); C = D(1:m,mn+1:X);'
The actual regular expression depends on the complete specification of the string.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by