4

given a cell array of strings, I want to build one regexprep rule, so that different string types are replaced by a certain number. I.e:

my_cell = {'ok', 'ok', 'bad', 'broken', 'bad', 'broken', 'ok'};

I know how to replace each string type one by one, i.e:

my_cell = regexprep(my_cell,'ok$','1');

but ideally I would like to build one rule, so that ok will be replaced with 1, bad will be replaced with 0 and broken will be replaced with -1.

any hints on how to do this?

2 Answers 2

4

How about:

>> my_cell = regexprep(my_cell,{'ok$','bad$','broken$'},{'1','0','-1'});
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't add a ^ since it was not needed in this case.
3

There's documentation here: http://www.mathworks.co.uk/help/techdoc/ref/regexprep.html

It gives the syntax as: s = regexprep('str', 'expr', 'repstr')

It also says: "If both expr and repstr are cell arrays of strings, then expr and repstr must contain the same number of elements, and regexprep pairs each repstr element with its matching element in expr."

Therefore you could try something like this:

my_cell = regexprep(my_cell, {'^ok$', '^bad$', '^broken$'}, {'1', '0', '-1'});

(Untested)

1 Comment

This example does not work because after the first regexp you change 'broken' to 'br1ken'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.