NSRegularExpression [英] NSRegularExpression

查看:133
本文介绍了NSRegularExpression的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:


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

我想得到<$的值c $ c> key ,我使用这个NSRegularExpression

(?i)(?< = key =)[。?!&] + [?=安培;]?

我认为模式就像匹配除&之外的任何字符。但结果总是 NULL

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.

除了&之外,每个键的值都可以包含任何内容。
那我怎样才能创建正确的NSRegularExpression?
谢谢。

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

推荐答案

你不应该使用正则表达式,特别是如果你不知道怎么做。比较:

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

这篇关于NSRegularExpression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆