MATLAB Answers

Extract Variables from mixed string

6 views (last 30 days)
Azar Nejad
Azar Nejad on 12 Aug 2018
Commented: Azar Nejad on 12 Aug 2018
Hi all,
In this string
'# Message: onset_pic1_8.png'
how can I read 'onset', 'pic', '1', '8' in four variables?

  1 Comment

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 12 Aug 2018
S = '# Message: onset_pic1_8.png';
parts = regexp(S, '(?<name1>[A-Za-z]+)_(?<name2>[A-Za-z]+)(?<num1>\d+)_(?<num2>\d+)', 'names')
parts =
struct with fields:
name1: 'onset'
name2: 'pic'
num1: '1'
num2: '8'
I coded to permit uppercase as well as lowercase, but I did assume that the alphabetic parts remain alphabetic and the numeric parts remain numeric.

  1 Comment

Azar Nejad
Azar Nejad on 12 Aug 2018
This works great many thanks
Azar

Sign in to comment.

More Answers (1)

Paolo
Paolo on 12 Aug 2018
Edited: Paolo on 12 Aug 2018
You can use:
mystring = '# Message: onset_pic1_8.png';
matches = regexp(mystring,'\d|[a-z]+(?=_|\d)','match')
>>matches
{'onset'} {'pic'} {'1'} {'8'}
To obtain the values.
You can't use 1 and 8 as variable names.

  0 Comments

Sign in to comment.

Sign in to answer this question.

Tags