MATLAB Answers

Liger
0

filter string in the string

Asked by Liger
on 21 Aug 2019 at 13:22
Latest activity Commented on by Liger
on 28 Aug 2019 at 19:42
Hello,
I am quietly new with matlab script.
I have a string as example.
str = 'this matlab is a good software, it is a version 9.4 which is equal to 2018a'
objective, I want to filter the number from that string ( so it is "9.4").
Note that I cannot see that number. All i want is to scan that number and show in my workspace.
so the scribt should read the text and identify the number of the version and show in my workspace.
I appreciate your help.
Regards,
LN

  2 Comments

Ted Shultz
on 21 Aug 2019 at 13:30
Do you not want to also get '2018'? What rule would the code use to exclude this?
Adam
on 21 Aug 2019 at 13:34
doc regexp
should help do this. It takes a bit of getting used to parameterising regular expressions though. There are likely simpler ways depending how robust you want it to be.

Sign in to comment.

3 Answers

Stephan
Answer by Stephan
on 21 Aug 2019 at 13:49
Edited by Stephan
on 21 Aug 2019 at 13:56
 Accepted Answer

str = 'this matlab is a good software, it is a version 9.4 which is equal to 2018a'
str = char(str);
idx = find((uint8(str)>=48 & uint8(str)<=57) | uint8(str)==46 | uint8(str)==32);
res = split(string(str(idx))," ");
res(res=="")=[]
The second line makes sure that it also works with:
str = "this matlab is a good software, it is a version 9.4 which is equal to 2018a"

  3 Comments

Guillaume
on 21 Aug 2019 at 14:00
The conversion to uint8 is a waste of time, you could just write
idx = find((str>=48 & str<=57) | str==46 | str==32);
even clearer:
idx = find((str>='0' & str<='9') | str=='.' | str==' ');
you could also use ismember:
idx = find(ismember(str, '0123456789. '));
Stephan
on 21 Aug 2019 at 14:06
thank you for the hint!
Liger
on 28 Aug 2019 at 19:42
Thank you, i found the anwser so useful

Sign in to comment.


Answer by Stephen Cobeldick on 21 Aug 2019 at 13:58
Edited by Stephen Cobeldick on 21 Aug 2019 at 14:01

>> str = 'this matlab is a good software, it is a version 9.4 which is equal to 2018a';
>> out = regexp(str,'\d+\.\d+','match','once')
out = 9.4

  1 Comment

Liger
on 28 Aug 2019 at 19:42
Thank you

Sign in to comment.


Guillaume
Answer by Guillaume
on 21 Aug 2019 at 14:09
Edited by Guillaume
on 21 Aug 2019 at 14:53

Using a regular expression:
numbers = regexp(youstring, '\<\d*\.?\d+\>', 'once')
which will extract any number not attached to text. Allowed formats for number is 123, 123.45, .123

  0 Comments

Sign in to comment.