regex replace whole word

6 次查看(过去 30 天)
Hi,
How to change
'v1 = v1a;'
to
'v(1) = v1a;'
using regex or regexrep?
regexprep('v1 = v1a','\bv1\b','v(1)')
apparently does not work.

采纳的回答

Stephen23
Stephen23 2018-6-1
编辑:Stephen23 2018-6-1
>> regexprep('v1 = v1a','^([a-z]+)(\d+)','$1($2)')
ans = v(1) = v1a
Hopefully you are not constructing arbitrary strings of code for evaluating!
  8 个评论
Bardo
Bardo 2018-6-1
I reckon the main requested feature - to replace only whole words matching the string - is well in the title but got lost in the discussion.
Stephen23
Stephen23 2018-6-1
@Bardo: you should accept your answer, if it resolves your original question.

请先登录,再进行评论。

更多回答(1 个)

Bardo
Bardo 2018-6-1
Here we go:
>> regexprep('v1 = v1a','\<v1\>','v(1)')
ans =
v(1) = v1a
or as a strrep for whole words
function snew = subsname(s, old, new)
snew = regexprep(s,['\<', old,'\>'], new);

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

产品


版本

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by