gpt4 book ai didi

regex - 在cocoa中解析URL

转载 作者:行者123 更新时间:2023-12-03 17:35:31 24 4
gpt4 key购买 nike

URL是: http://oauth.vk.com/blank.html#access_token=244832666666668A3MNA06F553247789a80224789a24555555553232323232323292IND193CIEN = 742

如何在Cocoa中解析它并获取access_tokenuser_id

最佳答案

NSURL有一个-fragment方法,它返回#后面的字符串。

这就是用途。它非常基本,不支持实体(如 &),它只是按 & 分割字符串,然后按 = 分割字符串。

@interface NSURL (SYBasicKeyValueParsing)
- (NSDictionary *)sy_keysAndValuesOfString:(NSString *)string;
- (NSDictionary *)sy_keysAndValuesOfFragment;
- (NSDictionary *)sy_keysAndValuesOfQuery;
@end

@implementation NSURL (SYBasicKeyValueParsing)

- (NSDictionary *)sy_keysAndValuesOfString:(NSString *)string
{
if (!string) return nil;

NSMutableDictionary *result = [NSMutableDictionary dictionary];

for (NSString *pair in [string componentsSeparatedByString:@"&"]) {
NSArray *keyAndValue = [pair componentsSeparatedByString:@"="];
if ([keyAndValue count] == 2) {
[result setObject:[keyAndValue objectAtIndex:1] forKey:[keyAndValue objectAtIndex:0]];
}
}
return [[result copy] autorelease];
}

- (NSDictionary *)sy_keysAndValuesOfFragment
{
return [self sy_keysAndValuesOfString:[self fragment]];
}

- (NSDictionary *)sy_keysAndValuesOfQuery
{
return [self sy_keysAndValuesOfString:[self query]];
}

@end

因此,您的 URL 的 sy_keysAndValuesOfFragment 将导致以下结果:

{
"access_token" = 244832666b8168a3mna06f03f5324789a8022455245532b032375f193ceab923;
"expires_in" = 86400;
"user_id" = 191742;
}

关于regex - 在cocoa中解析URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10959911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com