How to replace string that perfectly matchs the string?
1 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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;'
See Anchors: https://www.mathworks.com/help/matlab/ref/regexprep.html#btrbo5i_sep_shared-expression in the documentation.
3 个评论
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 Center 和 File Exchange 中查找有关 Annotations 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!