0

I am trying to develop a rules based string editing function in Matlab.

Suppose I have generated a string like the following:

myString = '/+*43/*/+34/5*2/*'

Supposed further that I wish to remove certain math operators according to a set of rules:

  1. A string cannot start with the '*' or '/' operators
  2. A string cannot end with any operator
  3. Any sequential operators are replaced by the first operator in that sequence unless it violates 1 and 2.

So for example the above string would reduce to:

myNewString = '+43/34/5*2'

Any method is fine to solve this problem, but a vectorized Boolean method would be preferred.

What I would like to do with this string is be able to perform a str2num on it and have it return a value and not throw errors.

Thanks!

1 Answers1

1

Regular expressions can be used here:

myString = '/*+*43/*/+34/5*2/*';
myString = regexprep(myString,'^[/*]+','');   % accomplish the rule #1
myString = regexprep(myString,'[/*+-]+$','');   % accomplish the rule #2
myString = regexprep(myString,'[/*+-]{2,}','${$0(1)}')   % accomplish the rule #3
AVK
  • 2,130
  • 3
  • 15
  • 25
  • Thank you! That is elegant. I was trying to use regular expressions as suggested by excaza in a rather hack method with while loops and empty set replacement, but this is much more simple. Seems like there is lots to learn in regular expressions! – Michael Varney Sep 25 '16 at 14:22