NS正则表达式

发布于 2024-12-04 22:06:31 字数 343 浏览 1 评论 0原文

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


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

我想获取key的值,我使用这个 NSRegularExpression <代码> (?i)(?<=key=)[.?!&]+[?=&]?? 我认为该模式就像匹配除“&”之外的任何字符。但结果始终为NULL

每个键的值可以是除“&”之外的任何值。 那么如何创建正确的 NSRegularExpression 呢? 谢谢。

I have a string like:


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

I want to get the value for the key,I use this NSRegularExpression

(?i)(?<=key=)[.?!&]+[?=&]??

What I think is that the pattern is like matching any character except "&".But the result is always NULL.

the value of each key can have anything except "&".
So How can I create the correct NSRegularExpression?
thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

狼性发作 2024-12-11 22:06:31

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

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]));
                                 }
                             }
                         }];
}

You shouldn't use a regex for this, specially if you don't know how. Compare:

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]));
                                 }
                             }
                         }];
}
凑诗 2024-12-11 22:06:31

我知道答案发布已经好几年了,但是虽然 Jano 答案中的代码在技术上是正确的,但多次调用 rangeOfString 效率非常低。

正则表达式实际上非常简单。您可以执行以下两项操作之一:

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];
}

请注意,在使用正则表达式时,使用双反斜杠 (\\) 来转义反斜杠实际代码。

I know it's been years since the answer was posted, but while the code in Jano's answer is technically correct, calling rangeOfString multiple time is very inefficient.

The regex is actually quite simple. You can do one of the two following:

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

The code in Objective-C using NSRegularExpression would look like this:

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];
}

or like this:

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];
}

Note the double backslash (\\) to escape the backslash when using the regex in actual code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文