Created
May 23, 2014 02:01
-
-
Save siqin/1fbbab57b4e4840a0a8d to your computer and use it in GitHub Desktop.
NSMutableString+UBBParser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface NSMutableString (UBBParser) | |
- (void)enumUBBTag:(NSString *)ubbTag usingBlock:(void (^)(NSRange tagRange, | |
NSString *tagContent, | |
NSMutableString *currentStr, | |
BOOL *stop))block; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "NSMutableString+UBBParser.h" | |
@implementation NSMutableString (UBBParser) | |
- (void)enumUBBTag:(NSString *)ubbTag usingBlock:(void (^)(NSRange tagRange, | |
NSString *tagContent, | |
NSMutableString *currentStr, | |
BOOL *stop))block | |
{ | |
NSString *reStr = [NSString stringWithFormat:@"\\[%@\\].*?\\[/%@\\]", ubbTag, ubbTag]; | |
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:reStr options:0 error:NULL]; | |
while (1) { | |
NSTextCheckingResult *result = [regex firstMatchInString:self options:0 range:NSMakeRange(0, self.length)]; | |
if (result == nil || result.range.location == NSNotFound) break; | |
NSRange range = result.range; | |
NSMutableString *content = [[NSMutableString alloc] initWithString:[self substringWithRange:range]]; | |
[content trimUBBTag:ubbTag]; | |
BOOL needStop = NO; | |
block(range, content, self, &needStop); | |
if (needStop) break; | |
} | |
} | |
#pragma mark - | |
- (void)trimUBBTag:(NSString *)ubbTag | |
{ | |
NSString *endUBBTag = [NSString stringWithFormat:@"[/%@]", ubbTag]; | |
NSRange endRange = NSMakeRange(self.length - endUBBTag.length, endUBBTag.length); | |
NSString *endSubStr = [self substringWithRange:endRange]; | |
NSString *startUBBTag = [NSString stringWithFormat:@"[%@]", ubbTag]; | |
NSRange startRange = NSMakeRange(0, startUBBTag.length); | |
NSString *startSubStr = [self substringWithRange:startRange]; | |
if ([endSubStr isEqualToString:endUBBTag]) { | |
[self replaceCharactersInRange:endRange withString:@""]; | |
} | |
if ([startSubStr isEqualToString:startUBBTag]) { | |
[self replaceCharactersInRange:startRange withString:@""]; | |
} | |
} | |
#pragma mark - | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment