本次的博客主要是介紹NSRegularExpression的用法、具體的正則表達式的書寫學習可以到百度搜索教程粒竖,也可以到http://www.regexlab.com/zh/regref.htm 里查閱與學習
源碼地址:https://github.com/chenfanfang/CollectionsOfExample
先附上一張運行結(jié)果圖片
附上UI搭建界面圖
附上代碼
//
// FFRegulationExpressVC.m
// CollectionsOfExample
//
// Created by mac on 16/7/31.
// Copyright ? 2016年 chenfanfang. All rights reserved.
//
#import "FFRegulationExpressDemoVC.h"
@interface FFRegulationExpressDemoVC ()
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UILabel *resultLabel;
@end
@implementation FFRegulationExpressDemoVC
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"正則表達式的使用";
}
/** 開始匹配 */
- (IBAction)beginMatching {
NSError *error = nil;
//正常的正則表達式是: "\$.{2,10}\(\w{8}\)\$" 由于轉(zhuǎn)義字符的原因雷激,\\代表一個\
/** 正則表達式 */
NSString *regularExpStr = @"\\$.{2,10}\\(\\w{8}\\)\\$";
NSRegularExpression *regularExp = [[NSRegularExpression alloc] initWithPattern:regularExpStr options:NSRegularExpressionCaseInsensitive error:&error];
/** 文本內(nèi)容字符串 */
NSString *conentStr = self.textView.text;
/** 結(jié)果的字符串 */
NSMutableString *resultStrM = [NSMutableString stringWithFormat:@"結(jié)果:\n"];
//開始匹配字符串
/*
//匹配方式1:返回匹配結(jié)果
NSArray <NSTextCheckingResult *> *resultArr = [regularExp matchesInString:conentStr options:NSMatchingReportProgress range:NSMakeRange(0, conentStr.length)];
//遍歷數(shù)組爹脾、取出匹配出來的字符串
for (NSTextCheckingResult *result in resultArr) {
NSString *subStr = [conentStr substringWithRange:result.range];
[resultStrM appendString:[NSString stringWithFormat:@"%@\n",subStr]];
}
*/
//匹配方式2:block快速遍歷每個匹配 stop可以控制退出遍歷
[regularExp enumerateMatchesInString:conentStr options:NSMatchingReportProgress range:NSMakeRange(0, conentStr.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
if (result) {
NSString *subStr = [conentStr substringWithRange:result.range];
[resultStrM appendString:[NSString stringWithFormat:@"%@\n",subStr]];
}
}];
self.resultLabel.text = resultStrM;
}
@end
對正則表達式$.{2,10}(\w{8})$ 進行拆分解釋