我们如何检查一个字符串是否只由数字组成。我正在从字符串中取出一个子字符串,并希望检查它是否是数值子字符串。
NSString *newString = [myString substringWithRange:NSMakeRange(2,3)];发布于 2011-05-23 07:13:59
这里有一种不依赖于尝试将字符串解析为数字的有限精度的方法:
NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
{
// newString consists only of the digits 0 through 9
}参见+[NSCharacterSet decimalDigitCharacterSet]和-[NSString rangeOfCharacterFromSet:]。
发布于 2011-05-23 07:10:12
我建议使用NSNumberFormatter类中的numberFromString:方法,如果数字无效,它将返回nil;否则,它将返回NSNumber。
NSNumberFormatter *nf = [[[NSNumberFormatter alloc] init] autorelease];
BOOL isDecimal = [nf numberFromString:newString] != nil;发布于 2016-02-16 15:19:57
使用以下方法-validateString:withPattern:通过正则表达式、模式"^[0-9]+$"进行验证。
[self validateString:"12345" withPattern:"^[0-9]+$"];如果"123.123“被认为是具有模式"^[0-9]+(.{1}[0-9]+)?$"的
如果恰好是4位数字,则为
"."。带有pattern "^[0-9]{4}$".的
如果数字没有"."且长度在2~ 5之间,则为
"^[0-9]{2,5}$".的
带减号的
"^-?\d+$"可以在the online web site中检查正则表达式。
helper函数如下。
// 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版本:
在操场上测试。
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)https://stackoverflow.com/questions/6091414
复制相似问题