Objective-C: Find numbers in string

前端 未结 7 1058
遇见更好的自我
遇见更好的自我 2020-11-27 04:37

I have a string that contains words as well as a number. How can I extract that number from the string?

NSString *str = @\"This is my string. #1234\";
         


        
7条回答
  •  离开以前
    2020-11-27 05:10

    You could use the NSRegularExpression class, available since iOS SDK 4.

    Bellow a simple code to extract integer numbers ("\d+" regex pattern) :

    - (NSArray*) getIntNumbersFromString: (NSString*) string {
    
      NSMutableArray* numberArray = [NSMutableArray new];
    
      NSString* regexPattern = @"\\d+";
      NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:regexPattern options:0 error:nil];
    
      NSArray* matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
      for( NSTextCheckingResult* match in matches) {
          NSString* strNumber = [string substringWithRange:match.range];
          [numberArray addObject:[NSNumber numberWithInt:strNumber.intValue]];
      }
    
      return numberArray; 
    }
    

提交回复
热议问题