Matlab: Find a string pattern and replace it by a random string

Viewed 59

Consider the string:

str = 'text text [[i]] text text [[i]]'

The [[i]] string should be replaced by a random integer, say 1 for the first [[i]] and 5 for the second [[i]]. Is there a way to achieve this in Matlab without relying on the split command?

The classical

newstrreg = regexprep(str, '\[\[i\]\]',num2str(rand(1)))

will replace all [[i]] in the same string by the same randomized value, which I do not want.

2 Answers

No, a callback method is not supported as a replacement argument. Do it in a loop replacing each match only once:

str = 'text text [[i]] text text [[i]]'
for i = 1:2
  str = regexprep(str, '\[\[i\]\]',num2str(rand(1)), 'once');
end

Output:

str = text text 0.8329 text text 0.87961

You can solve this with one regexprep call:

>> str = 'text text [[i]] text text [[i]]';
>> regexprep(str,'\[\[i\]\]','${string(rand)}')

ans =

    'text text 0.81472 text text 0.90579'
Related