在出现之间替换字符串

Dif*_*ffy 0 iphone objective-c nsstring ios

我有一个我想在uiwebview中显示的字符串,可能如下所示:

"blah blah blah [IMG]you.png[/IMG] blah blah [IMG]me.png[/IMG]"
Run Code Online (Sandbox Code Playgroud)

我希望它像这样取代:

"blah blah blah <img src=\"you.png\"> blah blah <img src=\"me.png\">"
Run Code Online (Sandbox Code Playgroud)

我已经可以获得[IMG] ... [/ IMG]之间的字符串问题是它只能获得第一组[IMG] ... [/ IMG]而其余的事件不能.

NSRange startRange = [finalQuestionString rangeOfString:@"[IMG]"];
if (startRange.location != NSNotFound) {
     NSRange targetRange;
     targetRange.location = startRange.location + startRange.length;
     targetRange.length = [finalQuestionString length] - targetRange.location;   
     NSRange endRange = [finalQuestionString rangeOfString:@"[/IMG]" options:0 
     range:targetRange];
     if (endRange.location != NSNotFound) {
         targetRange.length = endRange.location - targetRange.location;
         NSString *imageFile = [finalQuestionString 
         substringWithRange:targetRange];//the extracted filename
     }
}
Run Code Online (Sandbox Code Playgroud)

那么如何才能获得[IMG] ... [/ IMG]的所有事件并将其替换为

"<img src=\"file.png\">"
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.谢谢!

sos*_*orn 5

既然[IMG]永远变成<img src=\"[/IMG]永远变成\">",为什么不做这样的事情:

NSString *originalString = @"blah blah blah [IMG]you.png[/IMG] blah blah [IMG]me.png[/IMG]";
NSString *tempString = [originalString stringByReplacingOccurrencesOfString:@"[IMG]" withString:@"<img src=\""];
NSString *finalString = [tempString stringByReplacingOccurrencesOfString:@"\"[/IMG]" withString:@"\'>'"];
Run Code Online (Sandbox Code Playgroud)

内存管理留给读者:)