Objective-C NSRegularExpressions,查找字符串中数字的第一次出现

标签 objective-c ios regex cocoa nsregularexpression

我对 Objective-C 的正则表达式还很陌生。我遇到了一些困难。

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b([1-9]+)\\b" options:NSRegularExpressionCaseInsensitive error:&regError];
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

最佳答案

首先是正则表达式的问题:

  1. 您正在使用字边界 (\b),这意味着您只是 寻找一个独立的数字(例如 15 但不是 150A)。
  2. 您的号码范围不包括 0,因此它不会捕获 150。它需要是 [0-9]+ 并且最好使用 \d+

所以要解决这个问题,如果你想捕获任何数字,你只需要 \d+。如果您想捕获任何以数字开头的内容,则只需将单词边界放在开头 \b\d+

现在要获得第一次出现,您可以使用
-[regex rangeOfFirstMatchInString:options:range:]

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b\\d+" options:NSRegularExpressionCaseInsensitive error:&regError];
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);

关于Objective-C NSRegularExpressions,查找字符串中数字的第一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13092498/

相关文章:

ios - UITapGestureRecognizer - 检测双击或三次点击?

objective-c - 放大 ScrollView ios6

ios - 在 View Controller 之间传递数据

android - 如何在 Flutter 中使用本地资源播放音频?

iphone - 在自定义 UITableViewCell 中访问 UITextField

ios - 如何使用 Nib 执行到不同 View Controller 的 Segue?

java - 使用正则表达式替换全部不替换完整结果

java - 正则表达式中带有可选 block 的组编号

python re.search 返回 None 和 Object

iphone - 根据 iOS 版本有条件地包含 header