2013年6月20日 星期四

正規表示法 regular expression

大原則是分次取得包含內容的元素

最後才去掉標籤

當然情況比較複雜時就看需求了

以下會先使用 matchesInString 取得元素

然後用 replaceInString 將前後 tag 去掉留下中間的值

                

                NSString *aa = @"123123<span class=\"g\">span content</span>243242424";

                

                NSError *errRegex = NULL;

                

                NSRegularExpression *regex = [NSRegularExpression

                 regularExpressionWithPattern:@"<span class=\"g\">(.|\n)*?</span>"

                 options:NSRegularExpressionCaseInsensitive

                 error:&errRegex];

                

                NSUInteger countMatches = [regex numberOfMatchesInString:aa

                 options:0 range:NSMakeRange(0, [aa length])];

                [regex enumerateMatchesInString:aa options:0

                 range:NSMakeRange(0, [aa length])

                 usingBlock:^(NSTextCheckingResult *match,

                 NSMatchingFlags flags, BOOL *stop) {

                

                 NSLog(@"Ranges: %ld", [match numberOfRanges]);

                

                 NSString *matchFull = [aa substringWithRange:[match range]];

                 NSLog(@"Match: %@", matchFull);

                        

                        NSRegularExpression *regexx = [NSRegularExpression

                        regularExpressionWithPattern:@"<(.|\n)*?>"

                        options:NSRegularExpressionCaseInsensitive

                        error:&errRegex];

                        

                        NSString *modifiedString = [regexx

                                 stringByReplacingMatchesInString:matchFull

                                options:0 range:NSMakeRange(0, [matchFull length]) withTemplate:@""];

                        NSLog(@"%@", modifiedString);

                }];

                

                if (errRegex) {

                 NSLog(@"%@", errRegex);

                }

沒有留言: