0

我有一个 NSString 形式的对象

"this is [i]1[/i] and that is [i]2[/i] and there we have [i]3[/i], and so on"

[i]1[/i] 是对位于某处的图像编号 1 的引用。我想使用正则表达式匹配和替换来获得以下输出:

"this is <img src="root/1.png"> and that is <img src="root/2.png"> and there we have <img src="root/3.png">, and so on"

我使用一个NSRegularExpression类,但我认为我的正则表达式构造是错误的。请帮忙。

4

1 回答 1

0

您可能忘记正确转义括号。你必须逃脱他们两次。Objective-C 编译器会将单个反斜杠解释为字符串转义字符。要在正则表达式模式中插入反斜杠,您必须对其进行转义,即要匹配[您必须编写\\[.

NSString *string = @"this is [i]1[/i] and that is [i]2[/i] and there we have [i]3[/i], and so on";
NSString *pattern = @"\\[i\\]([0-9]+)\\[/i\\]";
NSString *replacement = @"<img src=\"root/$1.png\">";
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern 
                               options:0 error:nil];
NSString *replaced = [regexp stringByReplacingMatchesInString:string 
                                           options:0 
                                             range:NSMakeRange(0, string.length) 
                                      withTemplate:replacement];
于 2013-05-16T11:54:10.717 回答