介绍于配置
1.去RegexKitLite下载类库,解压出来会有一个例子包及2个文件,其实用到的就这2个文件,添加到工程中。
备用地址:
http://www.cocoachina.com/bbs/job.php?action-download-pid-135286-tid-18111-aid-11143.html
2.工程中添加libicucore.dylib frameworks。
3.现在所有的nsstring对象就可以调用RegexKitLite中的方法了。
简单例子
1。
// finds phone number in format nnn-nnnn-nnnn
( 1 )用Range 在TextView.text里找出format nnn-nnnn-nnnn
NSRange r; NSString *regEx = @"{3}-[0-9]{4}-[0-9]{4}"; r = [textView.text rangeOfString:regEx options:NSRegularExpressionSearch]; if (r.location != NSNotFound) { NSLog(@"Phone number is %@", [textView.text substringWithRange:r]); } else { NSLog(@"Not found."); }
( 2 )用String 在TextView.text里找出format nnn-nnnn-nnnn
NSString *regEx = @"{3}-[0-9]{4}-[0-9]{4}"; NSString *match = [textView.text stringByMatching:regEx]; if ([match isEqual:@""] == NO) { NSLog(@"Phone number is %@", match); } else { NSLog(@"Not found."); }
( 3 )替换
NSString *regEx = @"({3})-([0-9]{3}-[0-9]{4})"; NSString *replaced = [textView.text stringByReplacingOccurrencesOfRegex:regEx withString:@"($1) $2"];
( 4 )用空格拆开放到数组
NSString *searchString = @"This is neat."; NSString *regexString = @"\s+"; NSArray *splitArray = NULL; splitArray = [searchString componentsSeparatedByRegex:regexString]; // splitArray == { @"This", @"is", @"neat." }
( 5)创建数组
NSString *searchString = @"$10.23, $1024.42, $3099"; NSString *regexString = @"\$((\d+)(?:\.(\d+)|\.?))"; NSArray *matchArray = NULL; matchArray = [searchString componentsMatchedByRegex:regexString];
跟这个一样 -》 matchArray == { @"$10.23", @"$1024.42", @"$3099" };
NSLog(@"matchArray: %@", matchArray);
了解更多的参考:
http://regexkit.sourceforge.net/RegexKitLite/index.html#copyRegexToClipboardPreferences
正则表达式语法参考:
http://msdn.microsoft.com/zh-cn/library/ae5bf541.aspx