regexprep - may the replacement string contain a variable?

조회 수: 1 (최근 30일)
Alexander
Alexander 2012년 12월 13일
My problem:
Assume you have the following string: str='WBEi xx(i,BE)'; I want to replace BE by QQ, but only in the second substring xx(i,BE).
The problem is that QQ is stored in a variable, say q='QQ'.
If I would take the function strrep(str, 'BE', q) both occurances of BE are replaced by QQ: ans = 'WQQi xx(i,QQ)'
If I realize it with regexprep (explicitely using 'QQ'): regexprep(str, '(xx\(i,)BE(\))', '$1QQ$2' ) the result is the right one: ans = 'WBEi xx(i,QQ)' %only the second is replaced
But is it somehow possible to parse the variable q='QQ' to this or a similiar function, to do the job?
Thanks!

채택된 답변

Matt Fig
Matt Fig 2012년 12월 13일
Does this work?
regexprep(str, '(xx\(i,)BE(\))', ['$1',q,'$2'] )

추가 답변 (1개)

Alexander
Alexander 2012년 12월 13일
That's it. Many thanks.
Alex

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by