Cornelius Sicker
Cornelius Sicker

Reputation: 160

Matlab: How to replace dynamic part of string with regexprep

I have strings like

@(foo) 5 + foo.^2
@(bar) bar(1,:) + bar(4,:)

and want the expression in the first group of parentheses (which could be anything) to be replaced by x in the whole string

@(x) 5 + x.^2
@(x) x(1,:) + x(4,:)

I thought this would be possible with regexprep in one step somehow, but after reading the docu and fiddling around for quite a while, I have not found a working solution, yet.

I know, one could use two commands: First, grab the string to be matched with regexp and then use it with regexprep to replace all occurrences.

However, I have the gut feeling this should be somehow possible with the functionality of dynamic expressions and tokens or the like.

Upvotes: 2

Views: 97

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

Without the support of an infinite-width lookbehind, you cannot do that in one step with a single call to regexprep.

Use the first idea: extract the first word and then replace it with x when found in between word boundaries:

s = '@(bar) bar(1,:) + bar(4,:)';
word = regexp(s, '^@\((\w+)\)','tokens'){1}{1};
s = regexprep(s, strcat('\<',word,'\>'), 'x');

Output: @(x) x(1,:) + x(4,:)

The ^@\((\w+)\) regex matches the @( at the start of the string, then captures alphanumeric or _ chars into Group 1 and then matches a ). tokens option allows accessing the captured substring, and then the strcat('\<',word,'\>') part builds the whole word matching regex for the regexprep command.

Upvotes: 1

Related Questions