Changing letters to other letters with regexprep
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Ryoma Kawakami
le 28 Sep 2018
Commenté : Walter Roberson
le 28 Sep 2018
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.
0 commentaires
Réponse acceptée
Stephen23
le 28 Sep 2018
Modifié(e) : Stephen23
le 28 Sep 2018
>> str = 'a':'z'
str = abcdefghijklmnopqrstuvwxyz
>> old = 'bcd';
>> new = 'abc';
>> [X,Y] = ismember(str,old);
>> str(X) = new(Y(X))
str = aabcefghijklmnopqrstuvwxyz
Note that this works efficiently for any characters, not just a limited subset. In order to use regexprep you would probably need to use a dynamic replacement expression.
1 commentaire
Walter Roberson
le 28 Sep 2018
Well, any characters representable in the first 65536 code points ;-) If you have codepoints beyond that, such as Linear B or CJK Unified Ideograms like ? then you would need more work.
Plus de réponses (2)
OCDER
le 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 commentaires
Walter Roberson
le 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.
2 commentaires
Voir également
Catégories
En savoir plus sur Startup and Shutdown dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!