您的位置:首页 > 其它

RegexKitLite的使用

2014-04-29 23:53 204 查看
作用:正则表达式的iOS开源库

官方文档:http://regexkit.sourceforge.net/RegexKitLite/

正则表达式 30分钟入门教程:

中文:http://www.cnblogs.com/deerchao/archive/2006/08/24/zhengzhe30fengzhongjiaocheng.html

英文:http://www.codeproject.com/Articles/9099/The-Minute-Regex-Tutorial

使用:

1,github下载:https://github.com/samdeane/RegexKitLite

2,将RegexKitLite.h 和RegexKitLite.m导入到工程。

3,添加libicucore.dylib frameworks:工程 ->Targets ->Build Phases ->Link
Binary With Libarries。

(ARC设置:targets->build phases中修改compiler Flags。添加:-fobjc-arc,可以让项目支持arc。如果想让原来支持arc的不使用arc则添加-fno-objc-arc)

4,实例:对微博的#话题#、@ta、http://... 进行匹配和替换

#import <Foundation/Foundation.h>
#import "RegexKitLite.h"

int main(int argc, const char * argv[])
{
@autoreleasepool
{
//微博:@用户 http://.... #话题#

NSString *test = @"我在#话题#上课@麻子 你们@罗 在听吗?https://www.baidu.com";

//匹配@并且@后面可有n个字符(不包含空格)
NSString *regex = @"@\\w+";

//匹配#
regex = @"#\\w+#";

//匹配超链接:1,?表示匹配1次或0次。超链接的匹配是根据链接复杂度而定的。
regex = @"http(s)?://([A-Za-z0-9.?_-]+(/)?)*";

//把以上3个合成一个:使用或|隔开,每隔小单元格用小括号包含。
regex = @"(@\\w+)|(#\\w+#)|(http(s)?://([A-Za-z0-9.?_-]+(/)?)*)";

NSArray *regexArray = [test componentsMatchedByRegex:regex];

for (NSString *s in regexArray)
{
NSLog(@"匹配结果s:%@",s);
//字符串替换
NSString *target = [NSString stringWithFormat:@"<a href='%@'>%@<a>",s,s];
test = [test stringByReplacingOccurrencesOfString:s withString:target];
}
NSLog(@"替换后:%@",test);
}
return 0;
}


输出:

2014-04-30 11:27:06.340 regexKitLite[1269:303] 匹配结果s:#话题#
2014-04-30 11:27:06.342 regexKitLite[1269:303] 匹配结果s:@麻子
2014-04-30 11:27:06.342 regexKitLite[1269:303] 匹配结果s:@罗
2014-04-30 11:27:06.343 regexKitLite[1269:303] 匹配结果s:https://www.baidu.com
2014-04-30 11:27:06.343 regexKitLite[1269:303] 替换后:我在<a href='#话题#'>#话题#<a>上课<a href='@麻子'>@麻子<a> 你们<a href='@罗'>@罗<a> 在听吗?<a href='https://www.baidu.com'>https://www.baidu.com<a>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: