How to check if a line contains only numbers?
3 views (last 30 days)
Show older comments
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
Accepted Answer
Stephen23
on 28 Jul 2015
>> 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
More Answers (1)
dpb
on 28 Jul 2015
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.
0 Comments
See Also
Categories
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!