0

参考以下问题“ String contains string in objective-c ”,我有一个返回以下标头的 HTTP 服务器:

PS无法附上截图,因为我是新用户,而是使用块引用:(

HTTP 标头:{

-信息省略-

Server = "HTTP Client Suite (Test case number:21)";

我为从 HTTP 服务器获取响应而编写的代码块是:

 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    *- code omitted -*

     // **HTTP header field**

    // A dictionary containing all the HTTP header fields of the receiver
    // By examining this dictionary clients can see the “raw” header information returned by the server
    NSDictionary *headerField = [[NSDictionary alloc]initWithDictionary:[(NSHTTPURLResponse *)httpResponse allHeaderFields]];

    // Call headerField dictionary and format into a string
    NSString *headerString = [NSString stringWithFormat:@"%@", headerField];

    NSLog(@"HTTP Header: %@",headerString);

    // String to match (changeable) and temporary string to store variable
    NSString *stringToMatch = @"Test case number";
    NSString *tempString = @"";

    // Check if headerString contains a particular string
    // By finding and returning the range of the first occurrence of the given string (stringToMatch) within the receiver
    // If the string is not found/doesn't exists
    if ([headerString rangeOfString:stringToMatch].location == NSNotFound)
    {
        NSLog(@"Header does not contain the string: '%@'", stringToMatch);
        tempString = NULL;
        NSLog(@"String is %@", tempString);
    }
    else
    {
        NSLog(@"Header contains the string: '%@'", stringToMatch);
        tempString = stringToMatch;
        NSLog(@"String is '%@'", tempString);
    }

}

我在这里所做的是实际查看字符串“测试用例编号”是否存在。如果是这样,那么我想提取数字 21 并将其存储在使用 NSInteger 的变量中,现在的问题是数字是可变的而不是恒定的(它每次都会根据 HTTP 服务器返回的内容而改变),因此我在这种情况下,我无法使用我之前所做的相同方法来检查字符串中是否存在整数。

我该如何实现这一目标?提前致谢!

4

1 回答 1

0

您可以使用正则表达式从字符串中提取数字。我在这里使用的模式是"Test case number:<integer>".

首先创建一个正则表达式:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"Test case number:(\\d+)"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];

检查您的字符串是否与此正则表达式匹配:

NSString *string = @"HTTP Client Suite (Test case number:21)";
NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];

如果找到匹配项,则从原始字符串中提取它。首先从原始字符串中获取数字的范围(起始位置,长度),然后substringWithRange:在原始字符串上使用提取数字。这有点冗长:)

if (match) {
    NSRange range = [match rangeAtIndex:1];
    NSString *number = [string substringWithRange:range];
}

现在number应该包含您要查找的数字作为字符串。

于 2012-10-25T15:42:55.833 回答