从给定字符串中仅检索正整数

Retrieve only positive integers from a given string

我有以下实现,其中 comboKey 是我尝试检索整数的字符串。

例如,如果 comboKey2m1s,那么它是 returns @[@"2",@"1"];太完美了。

如果 comboKey0m2s 然后它 returns @[@"0",@"2"];,但是我不想 0。我只想要正数 @[@"2"];

+ (NSArray*)comboCategoryItems : (NSString*)comboKey
{        
  NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
  NSArray *outArray = [comboKey componentsSeparatedByCharactersInSet:nonDigitCharacterSet];
  outArray = [outArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];
  return outArray;
}

你犯了一点点错误。在谓词中,您检查字符串长度而不是值。只需像这样更改谓词 @"integerValue > 0" 您的代码将产生预期的结果。

这是另一种方法,使用正则表达式

NSRegularExpression * exp = [[NSRegularExpression alloc]initWithPattern:@"([1-9]([0-9])*)+" options:NSRegularExpressionDotMatchesLineSeparators error:nil];
NSString * text = @"80m254s";
NSMutableArray *resultArray = [NSMutableArray array];
[exp enumerateMatchesInString:text options:NSMatchingWithoutAnchoringBounds range:NSMakeRange(0, text.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
    [resultArray addObject:[text substringWithRange:[result range]]];
}];


NSLog(@"%@",resultArray);

对于 @"0m2s"

2017-07-15 22:31:18.576397 RegexTestingProject[21823:1942182] ( 2 )

对于@"80m254s"

2017-07-15 22:33:50.378485 RegexTestingProject[21826:1942829] ( 80, 254 )

对于@"080m254s"

2017-07-15 22:35:40.760626 RegexTestingProject[21828:1943403] ( 80, 254 )

希望对您有所帮助