NSString正则表达式查找和替换



构建一个需要在UIWebView对象中显示一些HTML字符串的iOS应用。我试图搜索,寻找一个模式,并与适当的链接到一个图像取代。图像链接是原始的,例如[pic:brand:123],其中pic总是pic, brand可以是任意字母数字,123也可以是任意非空白字母数字。

到目前为止,我已经尝试了一些,包括:
NSString *pattern = @"\[pic:([^\s:\]]+):([^\]])\]";

但是到目前为止都没有成功。

下面是一个示例代码:
NSString *str = @"veryLongHTMLSTRING";
NSLog(@"Original test: %@",[str substringToIndex:500]);
NSError *error = nil;
// use regular expression to replace the emoji
NSRegularExpression *regex = [NSRegularExpression
                                  regularExpressionWithPattern:@"\[pic:([^\s:\]]+):([^\]])\]"
                                  options:NSRegularExpressionCaseInsensitive error:&error];
if(error != nil){
    NSLog(@"ERror: %@",error);
}else{
    [regex stringByReplacingMatchesInString:str
                                    options:0
                                      range:NSMakeRange(0, [str length])
                               withTemplate:[NSString stringWithFormat:@"/%@/photo/%@.gif",
                                             IMAGE_BASE_URL, @"$1/$2"]];
NSLog(@"Replaced test: %@",[str substringToIndex:500]);

我看到两个错误:在regex模式的第二个捕获组中缺少+,它应该是

NSString *pattern = @"\[pic:([^\s:\]]+):([^\]]+)\]";

stringByReplacingMatchesInString返回一个新字符串,它不替换匹配的字符串。因此,您必须将结果赋值给一个新字符串,或者将replaceMatchesInString:options:range:withTemplate:NSMutableString一起使用。

修改后的代码

NSString *pattern = @"\[pic:([^\s:\]]+):([^\]]+)\]";
NSString *str = @"bla bla [pic:brand:123] bla bla";
NSLog(@"Original test: %@",str);
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:pattern
                              options:NSRegularExpressionCaseInsensitive error:&error];
if(error != nil){
    NSLog(@"ERror: %@",error);
} else{
    NSString *replaced = [regex stringByReplacingMatchesInString:str
                                    options:0
                                      range:NSMakeRange(0, [str length])
                               withTemplate:[NSString stringWithFormat:@"/%@/photo/%@.gif",
                                             @"IMAGE_BASE_URL", @"$1/$2"]];
    NSLog(@"Replaced test: %@",replaced);
}

产生输出

Original test: bla bla [pic:brand:123] bla bla
Replaced test: bla bla /IMAGE_BASE_URL/photo/brand/123.gif bla bla

您误解了模板应该如何形成。另外,stringByReplacingMatchesInString不会改变原始字符串。试试这个(已测试):

NSString *target = @"longHTML [pic:whatever:123] longHTMLcontinues";
NSMutableString *s = [target mutableCopy];
NSError *err = nil;
NSRegularExpression *expr = [NSRegularExpression regularExpressionWithPattern:@"\[pic\:([a-zA-Z0-9]*)\:([a-zA-Z0-9]*)\]" options:0 error:&err];
if (err) {
    NSLog(@"%@", err);
    exit(-1);
}
[expr replaceMatchesInString:s options:0 range:NSMakeRange(0, s.length) withTemplate:@"/photo/$1/$2.gif"];

最新更新