Finding out whether a string is numeric or not

前端 未结 18 1713
一个人的身影
一个人的身影 2020-12-07 15:24

How can we check if a string is made up of numbers only. I am taking out a substring from a string and want to check if it is a numeric substring or not.

NSS         


        
18条回答
  •  青春惊慌失措
    2020-12-07 15:47

    Yet another option:

    - (BOOL)isValidNumber:(NSString*)text regex:(NSString*)regex {
        @try {
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
            return [predicate evaluateWithObject:text];
        }
        @catch (NSException *exception) {
            assert(false); 
            return NO;
        }
    }
    

    Usage example:

    BOOL isValid = [self isValidNumber:@"1234" regex:@"^[0-9]+$"];
    

提交回复
热议问题