码迷,mamicode.com
首页 > 其他好文 > 详细

RegexKitLite的使用

时间:2014-07-22 23:05:12      阅读:419      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   os   


作用:正则表达式的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>





RegexKitLite的使用,码迷,mamicode.com

RegexKitLite的使用

标签:style   blog   http   color   使用   os   

原文地址:http://blog.csdn.net/isharestudio/article/details/24745451

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!