gpt4 book ai didi

ios - NSRegularExpression

转载 作者:行者123 更新时间:2023-12-01 17:27:48 26 4
gpt4 key购买 nike

我有一个像这样的字符串:


?key=123%252Bf-34Fa&name=John
?name=Johon&key=123%252Bf-34Fa

我想获取 key的值,我使用此NSRegularExpression
(?i)(?<=key=)[.?!&]+[?=&]??
我认为该模式类似于匹配除“&”以外的任何字符。但是结果始终是 NULL

每个键的值可以包含“&”以外的任何值。
那么,如何创建正确的NSRegularExpression?
谢谢。

最佳答案

您不应该为此使用正则表达式,特别是如果您不知道如何使用正则表达式。相比:

NSString *string = @"?name=Johon&key=123%252Bf-34Fa";
// NSString *string = @"?key=123%252Bf-34Fa&name=John";

// one way
NSRange range = [string rangeOfString:@"key="];
if (range.location!=NSNotFound){
string = [string substringFromIndex:NSMaxRange(range)];
range = [string rangeOfString:@"&"];
if (range.location!=NSNotFound){
string = [string substringToIndex:range.location];
}
}

// another way
__block NSString *keyValue = nil;
[[string componentsSeparatedByString:@"&"] enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop){
NSRange range = [object rangeOfString:@"key="];
if (range.location!=NSNotFound){
keyValue = [object substringFromIndex:range.location+range.length];
*stop = YES;
}
}];

// regex way
NSString *regexStr = @"[\\?&]key=([^&#]*)";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:&error];
// enumerate all matches
if ((regex==nil) && (error!=nil)){
NSLog( @"Regex failed for url: %@, error was: %@", string, error);
} else {
[regex enumerateMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop){
if (result!=nil){
// iterate ranges
for (int i=0; i<[result numberOfRanges]; i++) {
NSRange range = [result rangeAtIndex:i];
NSLog(@"%ld,%ld group #%d %@", range.location, range.length, i,
(range.length==0 ? @"--" : [string substringWithRange:range]));
}
}
}];
}

关于ios - NSRegularExpression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7442549/

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