MATLAB Answers

0

part of file name

Asked by ayman mounir on 18 Jul 2019
Latest activity Commented on by ayman mounir on 19 Jul 2019
If I have a file name such as ' Hello_World_2020 ', I want to take the part between the underscores ' world ', how I would do that.
Regards.

  0 Comments

Sign in to comment.

Products


Release

R2015b

4 Answers

Walter Roberson
Answer by Walter Roberson
on 18 Jul 2019
Edited by Walter Roberson
on 18 Jul 2019
 Accepted Answer

s = 'Hello_World_2020';
c = regexp(s, '_', 'split') ;
c{2}
You can also use strsplit() instead of regexp. On the other hand, strsplit() invokes regexp internally.

  3 Comments

ayman mounir on 19 Jul 2019
Thanks a lot, it works
Adam Danz
on 19 Jul 2019
"If I write s=Hello_World_year_2020. the answer would be 'Hallo_year'. what I should modify?"
@ayman, it's not clear what rules you're following.
  • "Hello_World_2020" --> "World": This removes everything before and after the underscores, including the underscores.
  • "Hello_World_year_2020" --> "Hello_year": This doesnt' follow that rule.
I think Walter's solution will come in handy but you'll need to explain the rule you're following.
ayman mounir on 19 Jul 2019
clear, thanks

Sign in to comment.


Adam Danz
Answer by Adam Danz
on 18 Jul 2019

s = 'Hello_World_2020';
c = regexp(s,'_(.*)_','tokens');
c = c{1}{1};
c =
'World'

  1 Comment

ayman mounir on 19 Jul 2019
It is really helpful, thank a lot

Sign in to comment.


madhan ravi
Answer by madhan ravi
on 18 Jul 2019

s=' Hello_World_2020 ';
[~,Wanted]=regexp(s,'_(.*)_','match','tokens');
Wanted{:}

  2 Comments

ayman mounir on 19 Jul 2019
Thanks, It is really helpful, woudl mind to explain how the exprsion works. for exmaple If I write s=Hello_World_year_2020. the answer would be 'Hallo_year'. what I should modify?
Regards
madhan ravi
on 19 Jul 2019
As Adam commented , I had the same thoughts too straight away.

Sign in to comment.


Jan
Answer by Jan
on 19 Jul 2019

s = ' Hello_World_2020 '
c = strsplit(s, '_')
c{2}

  0 Comments

Sign in to comment.