您可以尝试以下方法。您将不得不用您的正则表达式模式替换 regex_pattern。在您的情况下, regex_pattern 应该类似于@"\\s\\d\\dC"
(a whitespace character ( \\s
) 后跟一个数字 ( \\d
) 后跟一个 digit ( \\d
) 后跟一个大写字母C
。
NSRegularExpressionCaseInsensitive
如果您可以确定字母 C 永远不会是小写,您可能还希望删除该选项。
NSError *error = nil;
NSString *regex_pattern = @"\\s\\d\\dC";
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:regex_pattern
options:(NSRegularExpressionCaseInsensitive |
NSRegularExpressionDotMatchesLineSeparators)
error:&error];
NSArray *arrayOfMatches = [regex matchesInString:myString
options:0
range:NSMakeRange(0, [myString length])];
// arrayOfMatches now contains an array of NSRanges;
// now, find and extract the 2nd match as an integer:
if ([arrayOfMatches count] >= 2) // be sure that there are at least 2 elements in the array
{
NSRange rangeOfSecondMatch = [arrayOfMatches objectAtIndex:1]; // remember that the array indices start at 0, not 1
NSString *secondMatchAsString = [myString substringWithRange:
NSMakeRange(rangeOfSecondMatch.location + 1, // + 1 to skip over the initial space
rangeOfSecondMatch.length - 2)] // - 2 because we ignore both the initial space and the final "C"
NSLog(@"secondMatchAsString = %@", secondMatchAsString);
int temperature = [secondMatchAsString intValue]; // should be 32 for your sample data
NSLog(@"temperature = %d", temperature);
}