简体   繁体   中英

Selectively editing strings based on rules in Matlab

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM