Skip to content

Instantly share code, notes, and snippets.

@siqin
Created May 23, 2014 02:01
Show Gist options
  • Save siqin/1fbbab57b4e4840a0a8d to your computer and use it in GitHub Desktop.
Save siqin/1fbbab57b4e4840a0a8d to your computer and use it in GitHub Desktop.
NSMutableString+UBBParser
#import <Foundation/Foundation.h>
@interface NSMutableString (UBBParser)
- (void)enumUBBTag:(NSString *)ubbTag usingBlock:(void (^)(NSRange tagRange,
NSString *tagContent,
NSMutableString *currentStr,
BOOL *stop))block;
@end
#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