How to check if a line contains only numbers?

Hello,
I have a text file. I need to check if some lines contain only numbers and maybe string 'to'. For example '115;125to129;155';
If the line contains string character except for 'to', it should give error message. For example:
line = '115a;125;129;155;';
I have tried isnumeric(line), it always returns 0. But if I convert the string to number with str2num(line), it returns empty.
Is there any simple solution to this?

2 Comments

Except for 'to', can you post an example for this exception?
your line contains also ';'

Sign in to comment.

 Accepted Answer

>> spl = regexp('115;125to129;155','(\d|;|to)*','split');
>> isempty([spl{:}])
ans =
1
>> spl = regexp('115a;125;129;155;','(\d|;|to)*','split');
>> isempty([spl{:}])
ans =
0

1 Comment

This is such great and simple answer to my question. Thank you very much.

Sign in to comment.

More Answers (1)

Probably regular expressions are the clever way here, but my proficiency is such I always have to go dig around too long to get the matching expression right so a start otherwise would be something like...
any(ismember(upper(line),'A':'Z')
to find those with characters. Augment the second argument with whatever else could be found in the wild as needed.
If the two are not found in the same string together, the above and a test to locate the specific string 'to' are sufficient; if they're possibly there together, what's the desired result? If the other character(s) nullifies the line then it's straightforward to check the specific case.

Categories

Asked:

on 28 Jul 2015

Commented:

on 31 Jul 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!