How to extract a string before a number?
16 ビュー (過去 30 日間)
Hello everyone, I need to know how to extract a substring from strings given below such that as soon as it encounters a digit, it returns the substring before that.
str = 'abcd-xyzw-1.2.3.zip'
str2 = 'abcd_xyzw_2.3.1.zip'
it should then return the substring as
sub_str = 'abcd-xyzw-'
sub_str2 = 'abcd_xyzw_'
How can it be done?
Thanks in advance
その他の回答 (2 件)
Karim 2022 年 8 月 30 日
You can use the regexp function to find the indexes for the numbers. Then you can split the char array using that index (minus one so that you do not have that first number)
% define the string, note i used a char array as in the OP's question
str = 'abcd-xyzw-1.2.3.zip';
% use the regexp function to obtain the indexes of the numbers
[~,idx] = regexp(str,'(?<!\d)(\d)+(?!\d)','match');
% get the sub string by taking the first characters (minus 1 so that we
% don't copy the first number)
sub_str = str( 1:(idx(1)-1) )