NSString正则表达式查找和替换

sha*_*eck 1 regex objective-c ios

构建一个需要在UIWebView对象中显示一些HTML字符串的iOS应用程序.我正在尝试搜索,找到一个模式并替换为图像的正确链接.图像链接是原始的,例如[pic:brand:123],pic总是在哪里pic,brand可以是任何字母数字,并且123is也可以是任何非空白字母数字.

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

NSString *pattern = @"\\[pic:([^\\s:\\]]+):([^\\]])\\]";
Run Code Online (Sandbox Code Playgroud)

但到目前为止还没有一个工作.

这是一个示例代码:

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]);
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 8

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

NSString *pattern = @"\\[pic:([^\\s:\\]]+):([^\\]]+)\\]";
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

产生输出

Original test: bla bla [pic:brand:123] bla bla
Replaced test: bla bla /IMAGE_BASE_URL/photo/brand/123.gif bla bla
Run Code Online (Sandbox Code Playgroud)