解析markdown中的图片地址
程序员文章站
2022-07-13 23:27:41
...
1、RegularParser.h
#import <Foundation/Foundation.h> @interface RegularParser : NSObject + (NSArray *)imageUrlsInString:(NSString *)string trimedString:(NSString **)trimedString; @end
2、RegularParser.m
#import "RegularParser.h" static NSString *imageRegular = @"!\\[.*?\\]\()\\(.*?\\)"; @implementation RegularParser + (NSArray *)imageUrlsInString:(NSString *)string trimedString:(NSString **)trimedString { NSError *error; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:imageRegular options:NSRegularExpressionCaseInsensitive error:&error]; __block NSMutableArray *imagesArray = [NSMutableArray array]; __block NSMutableString *mutableString = [string mutableCopy]; __block NSInteger offset = 0; __block NSString *keyword = nil; __block NSString *imageUrl = nil; [regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, string.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange resultRange = [result range]; resultRange.location += offset; // image keyword = [regex replacementStringForResult:result inString:mutableString offset:offset template:@"$0"]; NSRange startRange = [keyword rangeOfString:@"]("]; if (startRange.length > 0) { NSRange range = NSMakeRange(startRange.location + startRange.length, keyword.length - (startRange.location + startRange.length + 1)); imageUrl = [keyword substringWithRange:range]; [imagesArray addObject:imageUrl]; } [mutableString replaceCharactersInRange:resultRange withString:@""]; offset -= resultRange.length; *trimedString = mutableString; }]; return imagesArray; } @end
3、示例
NSString *markdownString = @"![](http://dl2.iteye.com/upload/attachment/0105/4183/f2b93502-e02b-3259-9837-d3dd14151e9d.png) When I say Japanese-Chinese food I'm not referring to some new type of restaurant serving both Japanese and Chinese food. This means the restaurant serves Chinese food prepared for Japanese tastes. ![](http://dl2.iteye.com/upload/attachment/0103/6545/d0590cfe-bd18-3c25-8b1b-2190c0526b5c.png) This is **subuta** -- sweet and sour pork, this one photo showing the meal set (tenshoku in Japanese). It's one of many Chinese dishes this restaurant serves... and they have **A LOT**!"; NSLog(@"%@", [RegularParser imageUrlsInString:markdownString trimedString:&markdownString]);
推荐阅读
-
Word2007中快速批量提取文档中的图片省去一次一张的烦恼
-
ImageGetter 显示 Html 中的图片_html/css_WEB-ITnose
-
ubuntu 装配xampp,将php.ini文件中的allow_call_time_pass_reference=On后,打开网页提示下载保存网页不解析PHP
-
PHP中获取内网用户MAC地址(WINDOWS/linux)的实现代码_PHP教程
-
WordPress主题制作中自定义头部的相关PHP函数解析_PHP
-
解析mysql中如何获得数据库的大小_MySQL
-
PHP过滤和替换提交信息中的链接URL地址
-
解析如何修改phpmyadmin中的默认登陆超时时间
-
iOS json解析返回的数据中又html是不是后台写错了
-
解析mysql中UNIX_TIMESTAMP()函数与php中time()函数的区别_PHP教程