How to take first three characters of string
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Mekala balaji
am 23 Mai 2016
Bearbeitet: Guillaume
am 24 Mai 2016
Hi,
I have the below cell array:
MA0K123T0
MB0JHY210I9
AoTkU08
880KE21L
PMB456KU0
standard
MF0KET9
twist
MA0KL3
PMV09K
Now I want to filter as below:
If the name start with M or P, then take the first three characters otherwise keep original name. My output should be:
MA0
MB0
AoTkU08
880KE21L
PMB
standard
MF0
twist
MA0
PMV
0 Kommentare
Akzeptierte Antwort
Azzi Abdelmalek
am 23 Mai 2016
Bearbeitet: Azzi Abdelmalek
am 23 Mai 2016
str={'MA0K123T0'
'MB0JHY210I9'
'AoTkU08'
'880KE21L'
'PMB456KU0'}
out=cellfun(@(x) regexprep(x,'\<(M|P).+',x(1:3)),str,'un',0)
7 Kommentare
Azzi Abdelmalek
am 24 Mai 2016
This doesn't give the expected result (look at the new question in the hidden comment)
Azzi Abdelmalek
am 24 Mai 2016
We can use dynamic expressions
match_expr = '(M|P)([a-zA-Z]?)([a-zA-Z]?)(.+)'
replace_expr='$1$2$3'
regexprep(str, match_expr, replace_expr)
Weitere Antworten (1)
Guillaume
am 23 Mai 2016
Bearbeitet: Guillaume
am 24 Mai 2016
Azzi's answer with to regex call seems unnecessarily complicated to me. The cellfun is also not required. This simple regex will do:
str = {'MA0K123T0'
'MB0JHY210I9'
'AoTkU08'
'880KE21L'
'PMB456KU0'}
out = regexp(str, '^[MP].{2}|.*', 'match', 'once')
Which basically says match M or P (the [MP]) at the beginning of the string (the ^) followed by any two characters (the .{2}) and if that does not match, match everything (the |.*)
edit for your updated question:
out = regexp(str, '^[MP][A-Za-z]?[A-Za-z]?|.*', 'match', 'once')
0 Kommentare
Siehe auch
Kategorien
Mehr zu Cell Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!