RegexKitLite的介绍、安装与使用

一、介绍

在Mac开发过程中,很多时候我们需要用到正则表达式,然而Cocoa中的正则表达式的使用不是那么顺手,我们可以使用第三方库来实现正则表达式,而强大的第三方正则表达式库RegexKitLite,恰好能满足我们的需求。

二、安装

安装过程如下:

  • 1、打开RegexKitLite官网。
    网址在此:http://regexkit.sourceforge.net/

  • 2、Download。

RegexKitLite的介绍、安装与使用_第1张图片

  • 3、解压RegexKitLite-4.0.tar.bz2后,文件列表如下:

RegexKitLite的介绍、安装与使用_第2张图片

将RegexKitLite.h与RegexKitLite.m复制于工程内。

  • 4、设置-fno-objc-arc(使其支持ARC),如下图所示

RegexKitLite的介绍、安装与使用_第3张图片

  • 5、设置-licucore

RegexKitLite的介绍、安装与使用_第4张图片

三、使用

在这里,我列举出使用频率最高的几个函数并配合两个实例来介绍其功能。

  • 1、isMatchedByRegex。
- (NSString *)stringByMatching:(NSString *)regex;

参数regex表示正则表达式,实例如下:

//通过isMatchedByRegex方法来验证email是否合法
NSString *email = @"[email protected]";
NSString *regex = @"\\b([a-zA-Z0-9%_.+\\-]+)@([a-zA-Z0-9.\\-]+?\\.[a-zA-Z]{2,6})\\b";
if ([email isMatchedByRegex:regex]) {
    NSLog(@"完美!");
} else {
    NSLog(@"格式有误!");
}

输出结果如下(省略无用信息):

完美!
Program ended with exit code: 0
  • 2、stringByMatching。
- (NSString *)stringByMatching:(NSString *)regex capture:(NSInteger)capture

参数regex表示正则表达式,capture表示匹配选项。
capture为0时,表示返回第一次匹配的字符串,带完全匹配的结果
capture为1时,表示返回第一次匹配的结果中第一处模糊匹配的子字符串
capture为2时,表示返回第一次匹配的结果中第二处模糊匹配,依次类推。

实例如下:

//获取oauth_token、oauth_token_secret与name的值
NSString *htmlStr = @"oauth_token=1a1de4ed4fca40599c5e5cfe0f4fba97&oauth_token_secret=3118a84ad910967990ba50f5649632fa&name=foolshit";
NSString *regexString = @"oauth_token=(\\w+)&oauth_token_secret=(\\w+)&name=(\\w+)";
NSString *matchedString1 = [htmlStr stringByMatching:regexString capture:0L]; //返回第一次匹配的结果,带完全匹配的字符
NSString *matchedString2 = [htmlStr stringByMatching:regexString capture:1L]; //返回第一次匹配的结果中第1处模糊匹配,不带完全匹配的字符中
NSString *matchedString3 = [htmlStr stringByMatching:regexString capture:2L]; //返回第一次匹配的结果中第2处模糊匹配,
NSString *matchedString4 = [htmlStr stringByMatching:regexString capture:3L];

NSLog(@"%@",matchedString1);
NSLog(@"%@",matchedString2);
NSLog(@"%@",matchedString3);
NSLog(@"%@",matchedString4);

htmlStr = @"0_T123F_0_T2F_0_T3F_0";
NSString *regex = @"T123F";
NSString *result = [htmlStr stringByMatching:regex capture:0L];
NSLog(@"匹配结果:%@",result);

结果如下(去掉了无用信息):

oauth_token=1a1de4ed4fca40599c5e5cfe0f4fba97&oauth_token_secret=3118a84ad910967990ba50f5649632fa&name=foolshit
1a1de4ed4fca40599c5e5cfe0f4fba97
3118a84ad910967990ba50f5649632fa
foolshit
匹配结果:T123F
Program ended with exit code: 0
  • 3、captureComponentsMatchedByRegex。
- (NSArray *)captureComponentsMatchedByRegex:(NSString *)regex;

该方法通过Regex进行字串的比对,并且会将第一组比对出来的结果以NSArray返回。

  • 4、arrayOfCaptureComponentsMatchedByRegex
- (NSArray *)arrayOfCaptureComponentsMatchedByRegex:(NSString *)regex;

该方法一样会回传Regex所比对出来的字串群组,但会回传全部的配对组合。

  • 5、stringByReplacingOccurrencesOfRegex
- (NSString *)stringByReplacingOccurrencesOfRegex:(NSString *)regex withString:(NSString *)replacement;

将字串中与Regex配对的结果进行替换。

你可能感兴趣的:(其它)