how do I get a substring in iOS?

2020-04-26 23:28发布

问题:

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

回答1:

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];