How to extract a string before a number?

조회 수: 19(최근 30일)
Meenal 2022년 8월 30일
답변: Stephen23 2022년 8월 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 = ''
str2 = ''
it should then return the substring as
sub_str = 'abcd-xyzw-'
sub_str2 = 'abcd_xyzw_'
How can it be done?
Thanks in advance

채택된 답변

Chunru 2022년 8월 30일
str = '';
str2 = '';
idx = regexp(str, '\d');
sub_str = str(1:idx(1)-1)
sub_str = 'abcd-xyzw-'
idx = regexp(str2, '\d');
sub_str2 = str2(1:idx(1)-1)
sub_str2 = 'abcd_xyzw_'
  댓글 수: 1
Meenal 2022년 8월 30일
Thanks !! It worked.

댓글을 달려면 로그인하십시오.

추가 답변(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 = '';
% 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) )
substr = 'abcd-xyzw-'

Stephen23 2022년 8월 30일
The simple approach using REGEXP, without wasting time fiddling around with indices:
str = '';
sub_str = regexp(str,'^\D+','match','once')
sub_str = 'abcd-xyzw-'


Find more on Characters and Strings 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!

Translated by