0

次の質問「String contains string in Objective-c」を参照して、次のヘッダーを返す HTTP サーバーを使用しています。

PS私は新しいユーザーであるため、スクリーンショットを添付できません。代わりに引用符を使用しました:(

HTTP ヘッダー: {

-情報省略-

Server = "HTTP クライアント スイート (テスト ケース番号: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);
    }

}

ここで行っているのは、文字列 "Test case number" が存在するかどうかを実際に確認することです。もしそうなら、数値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 に答える