Changing letters to other letters with regexprep
Show older comments
I'm trying to change letters in a string to different ones with one line of code. I simplified my code down to the following:
regexprep('ab',{'a','b'},{'b','c'});
Ideally, this would output 'bc'. Currently, regexprep runs through the string twice and ends up outputting 'cc'.
Is there any way to prevent this from happening? Is it possible with regexprep? Also, I would prefer to keep the letters as strings, as I'm planning on using the 'preservecase' condition.
Accepted Answer
More Answers (2)
OCDER
on 28 Sep 2018
Note that regexprep will replace things Sequentially.
regexprep('ab',{'a','b'},{'b','c'});
ab -> bb -> cc
To fix, reverse order like this:
regexprep('ab',{'b', 'a'},{'c', 'b'});
ab -> ac -> bc
2 Comments
Ryoma Kawakami
on 28 Sep 2018
OCDER
on 28 Sep 2018
replace('a b c', {'a', 'b', 'c'}, {'c', 'a', 'b'})
Walter Roberson
on 28 Sep 2018
old = 'bcd';
new = 'abc';
lookup = char(0:255);
lookup(old+1) = new;
str = 'a':'z'
str = lookup(str+1)
You do not need to add 1 if you are willing to omit the possibility of char(0) being in the string.
Categories
Find more on MATLAB Coder in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!