回答が投稿されてから何年も経っていますが、Janoの回答のコードは技術的には正しいものの、何rangeOfString
度も呼び出すのは非常に非効率的です。
正規表現は実際には非常に単純です。次の2つのいずれかを実行できます。
key=([^&\s]+) // searches for the key
// matches all characters other than whitespace characters
// and ampersands
([^&?\s]+)=([^&\s]+) // searches for key/value pairs
// key matches all characters other than whitespace characters
// and ampersands and question marks
// value matches all characters other than whitespace characters
// and ampersands
Objective-Cを使用したコードは次のNSRegularExpression
ようになります。
NSString *stringToSearch = @"?name=John&key=123%252Bf-34Fa"
NSError *error;
NSRegularExpression *findKey = [NSRegularExpression regularExpressionWithPattern:@"key=([^&\\s]+)" options:0 error:&error];
if (error) {
// log error
}
NSString *keyValue;
NSTextCheckingResult *match = [findKey firstMatchInString:stringToSearch options:0 range:NSMakeRange(0, stringToSearch.length)];
if (match) {
NSRange keyRange = [match rangeAtIndex:1];
keyValue = [stringToSearch substring:keyRange];
}
またはこのように:
NSString *stringToSearch = @"?name=John&key=123%252Bf-34Fa"
NSError *error;
NSRegularExpression *findParameters = [NSRegularExpression regularExpressionWithPattern:@"([^&?\\s]+)=([^&\\s]+)" options:0 error:&error];
if (error) {
// log error
}
NSMutableDictionary *keyValuePairs = [[NSMutableDictionary alloc] init];
NSArray *matches = [findParameters matchesInString:stringToSearch options:0 range:NSMakeRange(0, stringToSearch.length)];
for (NSTextCheckingResult *match in matches) {
NSRange keyNameRange = [match rangeAtIndex:1];
NSRange keyValueRange = [match rangeAtIndex:2];
keyValuePairs[[stringToSearch substring:keyNameRange]] = [stringToSearch substring:keyValueRange];
}
実際のコードで正規表現を使用する場合は、バックスラッシュをエスケープするための二重バックスラッシュ(\\)に注意してください。