Reputation:
I just wanted to know how i can determine whether a NSString string has a number.
Upvotes: 0
Views: 206
Reputation: 7632
You can check whether a string has a number or not by using regex
NSString *search = @"23.3";
//regex for integer number -> ^[0-9]*$
//regex for integer and decimal number -> ^[0-9]+([\,\.][0-9]+)?$
NSString *pattern = @"(^[0-9]+([,.][0-9]+)?$)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:search options:0 range:NSMakeRange(0, search.length)];
if(match == nil){
NSLog(@"Not a number");
}else{
NSLog(@"Number");
}
Upvotes: 0
Reputation: 1019
You can use [NSNumberFormatter numberFromString: s];
and it will return nil if it is not a number.
NSString *s = @"2.5";
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * num = [formatter numberFromString:s];
[formatter release];
If num
is nil
it is not a number.
Link to docs on NSNumberFormatterStyle
Upvotes: 1