1

I have a string that contains some text:

 <p>ProductImage [height:60]</p>

and I want to extract just the 60 from it? The 60 is just an arbitrary value here

Slee
  • 27,498
  • 52
  • 145
  • 243
  • I would just cut off the first 24 characters and the last 5. Or use regex. – Blender Nov 30 '11 at 18:04
  • 1
    You need to make it clear if it's only in that particular case (

    ProductImage [height:60]

    ) or if it should cover extracting a number out of any string.
    – jbat100 Nov 30 '11 at 18:06
  • extracting the number from any text with a pattern of [height:60], where 60 can be any numeric value – Slee Nov 30 '11 at 18:10

1 Answers1

9

You can use an NSScanner, or search using an NSRegularExpression.

NSScanner* sc = [NSScanner scannerWithString:s];
int num;
[sc scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] 
                   intoString:nil];
[sc scanInt:&num];

Or:

int num;
NSError* err = nil;
NSRegularExpression* r = [NSRegularExpression regularExpressionWithPattern:@"\\d+"
                                                                   options:0 
                                                                     error:&err];
// error-checking omitted
for (NSTextCheckingResult* match in [r matchesInString:s 
                                               options:0 
                                                 range:NSMakeRange(0, [s length])])
    num = [[s substringWithRange: [match range]] intValue];
matt
  • 515,959
  • 87
  • 875
  • 1,141