我正在使用 Objective C 创建标记编辑器。我需要以下功能:
- 识别块的分界,例如
**block**
- 删除开始和结束“标签”,例如“下一个文本是
**bold**
” 变为“下一个文本为粗体”
- 确定新上下文中标记文本的开始和结束位置:“下一个文本是粗体”
编辑:
由于我将来可能会扩展语法(目前会非常有限),因此自顶向下进行解析非常重要,这样文本的开始和结束位置始终与结果文本相对应。因此,正则表达式可能不是最好的解决方案。
做这个的最好方式是什么?
最后使用正则表达式方法正则表达式套件精简版 http://regexkit.sourceforge.net/RegexKitLite/index.html
下面的代码尚未经过完全测试,但确实适用于 St3fan 指出的情况。
- (NSArray *) scanContent:(NSMutableString **)content {
NSMutableArray *tokens = [[NSMutableArray alloc] init];
NSArray *captureRegex = [[NSArray alloc] initWithObjects:
@"\\[\\[(.*?)\\]\\]",@"\\*\\*(.*?)\\*\\*", nil];
NSArray *tokenID = [[NSArray alloc] initWithObjects:
@"Italic",@"Bold", nil];
int index = 0;
for (NSString*capture in captureRegex) {
NSRange captureRange;
NSRange stringRange;
stringRange.location = 0;
stringRange.length = [*content length];
do {
captureRange = [*content rangeOfRegex:capture inRange:stringRange];
if ( captureRange.location != NSNotFound ) {
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:[tokenID objectAtIndex:index] forKey:@"Token"];
[dictionary setObject:[NSNumber numberWithInt:captureRange.location]
forKey:@"Start"];
[dictionary setObject:[NSNumber numberWithInt:captureRange.length]
forKey:@"Length"];
[tokens addObject:dictionary];
for (NSMutableDictionary *dict in tokens) {
NSNumber *nRange = [dict objectForKey:@"Start"];
int start = [nRange intValue];
if (start > captureRange.location) {
nRange = [NSNumber numberWithInt:start - 4]; // Removing 4 characters
[dict setObject:nRange forKey:@"Start"];
}
if (start == captureRange.location) {
NSString *data = [*content stringByMatching:capture options:RKLMultiline inRange:captureRange capture:1 error:NULL];
NSLog(@"data: %@",data);
[*content replaceOccurrencesOfRegex:capture withString:data range:captureRange];
NSLog(@"Replaced Content: %@",*content);
}
}
stringRange.location = captureRange.location + captureRange.length -4;
stringRange.length = [*content length] - stringRange.location;
}
}
while ( captureRange.location != NSNotFound );
index++;
}
return tokens;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)