找出一个string是否是数字
我们如何检查一个string是否只由数字组成。 我从string中取出一个子string,并想检查它是否是一个数字子string。
NSString *newString = [myString substringWithRange:NSMakeRange(2,3)];
这是一种不依赖于尝试将stringparsing为数字的有限精度的方法:
NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet]; if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound) { // newString consists only of the digits 0 through 9 }
请参阅+[NSCharacterSet decimalDigitCharacterSet]
和-[NSString rangeOfCharacterFromSet:]
。
我build议使用NSNumberFormatter类中的numberFromString:
方法,就好像这个数字是无效的,它将返回nil; 否则,它会返回给你一个NSNumber。
NSNumberFormatter *nf = [[[NSNumberFormatter alloc] init] autorelease]; BOOL isDecimal = [nf numberFromString:newString] != nil;
您可以创build一个NSScanner并简单地扫描string:
NSDecimal decimalValue; NSScanner *sc = [NSScanner scannerWithString:newString]; [sc scanDecimal:&decimalValue]; BOOL isDecimal = [sc isAtEnd];
查看NSScanner的文档以获取更多方法供您select。
我想最简单的方法来检查给定的string中的每个字符是数字可能是:
NSString *trimmedString = [newString stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]]; if([trimmedString length]) { NSLog(@"some characters outside of the decimal character set found"); } else { NSLog(@"all characters were in the decimal character set"); }
如果要完全控制可接受的字符,请使用其他NSCharacterSet工厂方法之一。
这个原始的问题是关于Objective-C的,但是它在Swift宣布几年之前就已经发布了。 所以,如果你来自Google,并正在寻找一个使用Swift的解决scheme,那么你可以这样做:
let testString = "12345" let badCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet if testString.rangeOfCharacterFromSet(badCharacters) == nil { print("Test string was a number") } else { print("Test string contained non-digit characters.") }
通过正则expression式,通过模式"^[0-9]+$"
,方法-validateString:withPattern:
[self validateString:"12345" withPattern:"^[0-9]+$"];
- 如果考虑“123.123”
- 使用模式
"^[0-9]+(.{1}[0-9]+)?$"
- 使用模式
- 如果正好是4位数字,没有
"."
。- 模式为
"^[0-9]{4}$"
。
- 模式为
- 如果没有
"."
数字 ,长度在2〜5之间。- 模式为
"^[0-9]{2,5}$"
。
- 模式为
正则expression式可以在在线网站中查看 。
帮手function如下。
// Validate the input string with the given pattern and // return the result as a boolean - (BOOL)validateString:(NSString *)string withPattern:(NSString *)pattern { NSError *error = nil; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error]; NSAssert(regex, @"Unable to create regular expression"); NSRange textRange = NSMakeRange(0, string.length); NSRange matchRange = [regex rangeOfFirstMatchInString:string options:NSMatchingReportProgress range:textRange]; BOOL didValidate = NO; // Did we find a matching range if (matchRange.location != NSNotFound) didValidate = YES; return didValidate; }
Swift 3版本:
在操场上testing。
import UIKit import Foundation func validate(_ str: String, pattern: String) -> Bool { if let range = str.range(of: pattern, options: .regularExpression) { let result = str.substring(with: range) print(result) return true } return false } let a = validate("123", pattern: "^[0-9]+") print(a)
要清楚,这个函数为整数string。
inheritance人基于约翰的答案上面的小帮手类别:
在.h文件中
@interface NSString (NumberChecking) +(bool)isNumber:(NSString *)string; @end
在.m文件中
#import "NSString+NumberChecking.h" @implementation NSString (NumberChecking) +(bool)isNumber { if([self rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location == NSNotFound) { return YES; }else { return NO; } } @end
用法:
#import "NSString+NumberChecking.h" if([someString isNumber]) { NSLog(@"is a number"); }else { NSLog(@"not a number"); }
Swift 3的解决scheme可能是这样的:
extension String { var doubleValue:Double? { return NumberFormatter().number(from:self)?.doubleValue } var integerValue:Int? { return NumberFormatter().number(from:self)?.intValue } var isNumber:Bool { get { let badCharacters = NSCharacterSet.decimalDigits.inverted return (self.rangeOfCharacter(from: badCharacters) == nil) } } }
testing一个string是一个数字可能会有帮助
int i = [@"12.3" rangeOfCharacterFromSet: [ [NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet] ].location; if (i == NSNotFound) { //is a number }
快速扩展:
extension NSString { func isNumString() -> Bool { let numbers = NSCharacterSet(charactersInString: "0123456789.").invertedSet let range = self.rangeOfCharacterFromSet(numbers).location if range == NSNotFound { return true } return false } }
又一个select:
- (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; } }
用法示例:
BOOL isValid = [self isValidNumber:@"1234" regex:@"^[0-9]+$"];
对于Swift 3
var onlyDigits: CharacterSet = CharacterSet.decimalDigits.inverted if testString.rangeOfCharacter(from: onlyDigits) == nil { // String only consist digits 0-9 }
Swift 3解决scheme,如果需要validationstring只有数字:
CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: myString))
@John Calsbeek的回答的延伸,并澄清@Jeff和@gyratory马戏团的评论。
+ (BOOL)doesContainDigitsOnly:(NSString *)string { NSCharacterSet *nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet]; BOOL containsDigitsOnly = [string rangeOfCharacterFromSet:nonDigits].location == NSNotFound; return containsDigitsOnly; } + (BOOL)doesContainNonDigitsOnly:(NSString *)string { NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet]; BOOL containsNonDigitsOnly = [string rangeOfCharacterFromSet:digits].location == NSNotFound; return containsNonDigitsOnly; }
可以添加以下内容作为NSString
类别方法
- (BOOL)doesContainDigitsOnly { NSCharacterSet *nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet]; BOOL containsDigitsOnly = [self rangeOfCharacterFromSet:nonDigits].location == NSNotFound; return containsDigitsOnly; } - (BOOL)doesContainNonDigitsOnly { NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet]; BOOL containsNonDigitsOnly = [self rangeOfCharacterFromSet:digits].location == NSNotFound; return containsNonDigitsOnly; }