[英]Objective-C NSRegularExpressions, finding first occurrence of numbers in a string
使用Objective-C,我对正则表达式非常环保。 我遇到了一些困难。
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b([1-9]+)\\b" options:NSRegularExpressionCaseInsensitive error:®Error];
if (regError) {
NSLog(@"%@",regError.localizedDescription);
}
__block NSString *foundModel = nil;
[regex enumerateMatchesInString:self.model options:kNilOptions range:NSMakeRange(0, [self.model length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) {
foundModel = [self.model substringWithRange:[match rangeAtIndex:0]];
*stop = YES;
}];
我要做的就是拿一个字符串
150A
得到
150
首先是正则表达式的问题:
\\b
),这意味着您只需要查找单独的数字(例如15而不是150A)。 0
因此不会捕获150
。 它需要是[0-9]+
并且更好地使用\\d+
。 所以要解决这个问题,如果你想捕获任何数字,你需要的是\\d+
。 如果你想捕获任何以数字开头的东西,那么只将字边界放在开头\\b\\d+
。
现在,您可以使用第一次出现
-[regex rangeOfFirstMatchInString:options:range:]
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b\\d+" options:NSRegularExpressionCaseInsensitive error:®Error];
if (regError) {
NSLog(@"%@",regError.localizedDescription);
}
NSString *model = @"150A";
NSString *foundModel = nil;
NSRange range = [regex rangeOfFirstMatchInString:model options:kNilOptions range:NSMakeRange(0, [model length])];
if(range.location != NSNotFound)
{
foundModel = [model substringWithRange:range];
}
NSLog(@"Model: %@", foundModel);
怎么样.*?(\\d+).*?
?
演示:这将反向引用数字,您可以在任何地方使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.