NSString正则表达式查找和替换

时间:2013-01-13 16:14:46

标签: ios objective-c regex

构建一个需要在UIWebView对象中显示一些HTML字符串的iOS应用程序。我正在尝试搜索,找到一个模式并替换为图像的正确链接。图片链接是原始的[pic:brand:123],其中pic始终是picbrand可以是任何字母数字,123也可以是任何非字母数字-whitespace字母数字。

到目前为止,我尝试了一些包括:

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]);

2 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:2)

你误解了应该如何形成模板。此外,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"];