次のようなものを試すことができます。regex_pattern を正規表現パターンに置き換える必要があります。あなたの場合、regex_pattern は@"\\s\\d\\dC"
(空白文字 ( \\s
) の後に数字 ( \\d
) が続き、その後に数字 ( \\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);
}