正则表达式,常用于文件搜索和数据校验等
iOS 提供了对正则表达式的支持:NSRegularExpression
常用的第三方正则库regexkit有全面的介绍(英文):
http://regexkit.sourceforge.net/RegexKitLite/index.html
这个需要很长时间研究和总结积累的。
找的资料以备以后回头看
swift相关的正则表达式 网址是:http://www.raywenderlich.com/86205/nsregularexpression-swift-tutorial
下面的代码是还没有整理的:
1 #import <Foundation/Foundation.h>
2
3 int main(int argc, const char * argv[]) {
4 @autoreleasepool {
5 //1
6 NSString *email1 = @"heyang_asd@163.com";
7 NSString *regex1 = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
8 NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex1];
9 BOOL isValid1 = [predicate1 evaluateWithObject:email1];
10 NSLog(@"%hhd",isValid1);
11 //2
12 NSString *searchText = @"// Do any additional setup after loading the view, 22typically from a nib. come on, 2111111from a nib.";
13 // NSRange range = [searchText rangeOfString:@"(?:[^,])*\\s" options:NSRegularExpressionSearch];
14 NSRange range = [searchText rangeOfString:@"\\s" options:NSRegularExpressionSearch];
15 if (range.location != NSNotFound) {
16 NSLog(@"%@", [searchText substringWithRange:range]);
17 }
18 //3
19 // NSString *searchText3 = @"1 23456789, 123456789a.to the moon";//@"(?:[^,])*\\b"
20 NSString *searchText3 = @"to the moon";//@"\\b"匹配的是无,但是@"to\\b"还是有的
21 NSError *error = NULL;
22 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b" options:NSRegularExpressionCaseInsensitive error:&error];
23 NSTextCheckingResult *result = [regex firstMatchInString:searchText3 options:0 range:NSMakeRange(0, [searchText3 length])];
24 if (result) {
25 NSLog(@"%@\n", [searchText3 substringWithRange:result.range]);
26 NSLog(@"%lu",(unsigned long)result.range.length);
27 }else{
28 NSLog(@"no on");
29 }
30 //4查找所有的range
31 NSArray *matches = [regex matchesInString:searchText3
32 options:0
33 range:NSMakeRange(0, [searchText3 length])];
34 for (NSTextCheckingResult *match in matches) {
35 NSRange matchRange = [match range];
36 NSLog(@"查找所有的range:(位置)%lu 和 (长度)%lu",(unsigned long)matchRange.location,(unsigned long)matchRange.length);
37 // NSRange firstHalfRange = [match rangeAtIndex:1];
38 // NSLog(@"%lu",(unsigned long)firstHalfRange.length);
39 // NSRange secondHalfRange = [match rangeAtIndex:2];
40 // NSLog(@"%lu",(unsigned long)secondHalfRange.length);
41 }
42 //5
43 }
44 return 0;
45 }
46 /*
47 *使用系统的正则表达式类(NSRegularExpression)会返回匹配的多个结果。
48
49 小结:
50 第一种匹配需要学习NSPredicate的写法,需要查阅苹果相关技术文档;如果只关心第一个匹配的结果,第二种匹配较为简洁;如果需要匹配多个结果,同时匹配多次,第三种方式效率会更高。
51 */
匹配中文字符的正则表达式: [\u4e00-\u9fa5]
评注:匹配中文还真是个头疼的事,有了这个表达式就好办了
匹配双字节字符(包括汉字在内):[^\x00-\xff]
评注:可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)
匹配空白行的正则表达式:\n\s*\r
评注:可以用来删除空白行
匹配HTML标记的正则表达式:<(\S*?)[^>]*>.*?</\1>|<.*? />
评注:网上流传的版本太糟糕,上面这个也仅仅能匹配部分,对于复杂的嵌套标记依旧无能为力
匹配首尾空白字符的正则表达式:^\s*|\s*$
评注:可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式
匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
评注:表单验证时很实用
匹配网址URL的正则表达式:[a-zA-z]+://[^\s]*
评注:网上流传的版本功能很有限,上面这个基本可以满足需求
匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$
评注:表单验证时很实用
匹配国内电话号码:\d{3}-\d{8}|\d{4}-\d{7}
评注:匹配形式如 0511-4405222 或 021-87888822
匹配腾讯QQ号:[1-9][0-9]{4,}
评注:腾讯QQ号从10000开始
匹配中国邮政编码:[1-9]\d{5}(?!\d)
评注:中国邮政编码为6位数字
匹配身份证:\d{15}|\d{18}
评注:中国的身份证为15位或18位
匹配ip地址:\d+\.\d+\.\d+\.\d+
评注:提取ip地址时有用
匹配特定数字:
^[1-9]\d*$ //匹配正整数
^-[1-9]\d*$ //匹配负整数
^-?[1-9]\d*$ //匹配整数
^[1-9]\d*|0$ //匹配非负整数(正整数 + 0)
^-[1-9]\d*|0$ //匹配非正整数(负整数 + 0)
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$ //匹配正浮点数
^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$ //匹配负浮点数
^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$ //匹配浮点数
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$ //匹配非负浮点数(正浮点数 + 0)
^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$ //匹配非正浮点数(负浮点数 + 0)
评注:处理大量数据时有用,具体应用时注意修正
匹配特定字符串:
^[A-Za-z]+$ //匹配由26个英文字母组成的字符串
^[A-Z]+$ //匹配由26个英文字母的大写组成的字符串
^[a-z]+$ //匹配由26个英文字母的小写组成的字符串
^[A-Za-z0-9]+$ //匹配由数字和26个英文字母组成的字符串
^\w+$ //匹配由数字、26个英文字母或者下划线组成的字符串
评注:匹配中文还真是个头疼的事,有了这个表达式就好办了
匹配双字节字符(包括汉字在内):[^\x00-\xff]
评注:可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)
匹配空白行的正则表达式:\n\s*\r
评注:可以用来删除空白行
匹配HTML标记的正则表达式:<(\S*?)[^>]*>.*?</\1>|<.*? />
评注:网上流传的版本太糟糕,上面这个也仅仅能匹配部分,对于复杂的嵌套标记依旧无能为力
匹配首尾空白字符的正则表达式:^\s*|\s*$
评注:可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式
匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
评注:表单验证时很实用
匹配网址URL的正则表达式:[a-zA-z]+://[^\s]*
评注:网上流传的版本功能很有限,上面这个基本可以满足需求
匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$
评注:表单验证时很实用
匹配国内电话号码:\d{3}-\d{8}|\d{4}-\d{7}
评注:匹配形式如 0511-4405222 或 021-87888822
匹配腾讯QQ号:[1-9][0-9]{4,}
评注:腾讯QQ号从10000开始
匹配中国邮政编码:[1-9]\d{5}(?!\d)
评注:中国邮政编码为6位数字
匹配身份证:\d{15}|\d{18}
评注:中国的身份证为15位或18位
匹配ip地址:\d+\.\d+\.\d+\.\d+
评注:提取ip地址时有用
匹配特定数字:
^[1-9]\d*$ //匹配正整数
^-[1-9]\d*$ //匹配负整数
^-?[1-9]\d*$ //匹配整数
^[1-9]\d*|0$ //匹配非负整数(正整数 + 0)
^-[1-9]\d*|0$ //匹配非正整数(负整数 + 0)
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$ //匹配正浮点数
^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$ //匹配负浮点数
^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$ //匹配浮点数
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$ //匹配非负浮点数(正浮点数 + 0)
^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$ //匹配非正浮点数(负浮点数 + 0)
评注:处理大量数据时有用,具体应用时注意修正
匹配特定字符串:
^[A-Za-z]+$ //匹配由26个英文字母组成的字符串
^[A-Z]+$ //匹配由26个英文字母的大写组成的字符串
^[a-z]+$ //匹配由26个英文字母的小写组成的字符串
^[A-Za-z0-9]+$ //匹配由数字和26个英文字母组成的字符串
^\w+$ //匹配由数字、26个英文字母或者下划线组成的字符串
下面也是待整理的代码 (有关扩展NSString实例的类别):
<1>NSString+MatchPattern.h
1 /*
2 要记得在需要使用这个自定义的类别的类的时候要:
3 #import "NSString+MatchPattern.h"
4 */
5 #import <Foundation/Foundation.h>
6
7 @interface NSString (MatchPattern)
8
9
10 -(BOOL)isHasSubNSString:(NSString*)pattern;
11
12 -(BOOL)isValidata:(NSString*)pattern;
13
14 -(BOOL)isValidateEmail;
15
16 -(BOOL)isValidateTelNumber;
17 @end
<2>NSString+MatchPattern.m
1 //
2 // NSString+MatchPattern.m
3 // OC_Regex_Note
4 //
5 // Created by HEYANG on 15/8/1.
6 // Copyright (c) 2015年 HEYANG. All rights reserved.
7 //
8 /*
9 拓展NSString类的方法
10 用途:
11 1、验证用户输入是否正确。
12 各种各样的情况都列成一个方法。使用 NSPredicate 对整体输入进行判断
13
14 2、匹配是否含有目标子字符串 isHasSubNSString() findSubNSString()
15
16 3、根据findSubNSString()对应输出子字符串 getSubNSString()
17
18 4、获取所有的匹配对应的目标子字符串
19
20 5、获取匹配对应的目标子字符串的个数
21
22 6、自定义传入正则规则,获取匹配子字符串
23
24 7、option:1是否区分大小写2是否需要左右两边有间隔区分
25
26 8、
27 */
28
29 #import "NSString+MatchPattern.h"
30
31 @implementation NSString (MatchPattern)
32 //1创建一个 regex 对象
33 +(NSRegularExpression *)regexInstance:(NSString*)regularExpressionWithPattern {
34 NSError *error = NULL;
35 //先默认 不设置 任何option对象
36 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regularExpressionWithPattern options:0 error:&error];
37 if (error) {
38 NSLog(@"Regex对象创建失败。");
39 }
40 return regex;
41 }
42
43 //2是否 含有 子字符串
44 -(BOOL)isHasSubNSString:(NSString*)pattern{
45
46 NSString *beforeStr = self;
47 //方法1:
48
49 NSRange range = NSMakeRange(0, beforeStr.length);
50 NSUInteger n = [[NSString regexInstance:pattern] numberOfMatchesInString:beforeStr options:0 range:range];
51 NSLog(@"子字符串的个数:%zi",n);
52 if (n > 0) {
53 return true;
54 }else{
55 return false;
56 }
57 }
58 //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
59 //根据传入的正则表达式模式 来 判断是否合法
60 -(BOOL)isValidata:(NSString*)pattern{
61 BOOL isValiable = [NSString isValidateRegularExpression:self byExpression:pattern];
62 return isValiable;
63 }
64 +(BOOL)isValidateRegularExpression:(NSString *)strDestination byExpression:(NSString *)strExpression
65 {
66 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", strExpression];
67 return [predicate evaluateWithObject:strDestination];
68 }
69 //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
70 //这里就可以拓展很多功能
71 //验证email
72 -(BOOL)isValidateEmail{
73 NSString *strRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{1,5}";
74 return [self isValidata:strRegex];
75 }
76
77 //验证电话号码
78 -(BOOL)isValidateTelNumber {
79 NSString *strRegex = @"[0-9]{11,11}";
80 return [self isValidata:strRegex];
81 }
82 //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
83 @end
<3>main.m
1 #import <Foundation/Foundation.h>
2 #import "NSString+MatchPattern.h"
3
4 int main(int argc, const char * argv[]) {
5 @autoreleasepool {
6
7 //验证电话号码是否有用
8 NSString *telNumber = @"18720987504";
9 if ([telNumber isValidateTelNumber]) {
10 NSLog(@"电话号码合理。");
11 }
12 }
13 return 0;
14 }
![](http://static.oschina.net/uploads/img/201603/11164953_laMh.gif)
![](http://static.oschina.net/uploads/img/201603/11164953_R2AI.gif)
1 typedef NS_OPTIONS(NSUInteger, NSRegularExpressionOptions) {
2 NSRegularExpressionCaseInsensitive = 1 << 0, /* Match letters in the pattern independent of case. */
3 NSRegularExpressionAllowCommentsAndWhitespace = 1 << 1, /* Ignore whitespace and #-prefixed comments in the pattern. */
4 NSRegularExpressionIgnoreMetacharacters = 1 << 2, /* Treat the entire pattern as a literal string. */
5 NSRegularExpressionDotMatchesLineSeparators = 1 << 3, /* Allow . to match any character, including line separators. */
6 NSRegularExpressionAnchorsMatchLines = 1 << 4, /* Allow ^ and $ to match the start and end of lines. */
7 NSRegularExpressionUseUnixLineSeparators = 1 << 5, /* Treat only \n as a line separator (otherwise, all standard line separators are used). */
8 NSRegularExpressionUseUnicodeWordBoundaries = 1 << 6 /* Use Unicode TR#29 to specify word boundaries (otherwise, traditional regular expression word boundaries are used). */
9 };
10 NSRegularExpressionCaseInsensitive 大小写不敏感 ,当需要忽略大小写的时候,添加这个属性
11 NSRegularExpressionAllowCommentsAndWhitespace 允许注释和空格
12 NSRegularExpressionIgnoreMetacharacters 忽略元字符
13 NSRegularExpressionDotMatchesLineSeparators 点与线分隔符
14 NSRegularExpressionAnchorsMatchLines 锚匹配行
15 NSRegularExpressionUseUnixLineSeparators 使用Unix行分隔符
16 NSRegularExpressionUseUnicodeWordBoundaries 使用Unicode单词边界