MATLAB: How to extract the first part of an array of strings by pattern

MATLAB

Hi,
I have an array of strings: L_Name. Each string has several "_" in it. I would like to have an array that take the first part in each string by '_'. I tried to use strfind, or reg, but just cannot get it.
How to do that? Thanks! JF

Best Answer

If you want the part of the string before the first underscore '_', then you can use regexp:
>> C = {'L_Name','Z_Y_X','Aaaa_BBBB','MMM'};
>> D = regexp(C,'[^_]+','once','match');
>> D{:}
ans = L
ans = Z
ans = Aaaa
ans = MMM
>>