What is a regular form?
正則表達式是对字符串操作的一种逻辑公式。
Role?
在iOS开发中我们通常使用正則表達式来匹配给定的字符串是否符合我们的业务逻辑,比方说用户注冊帐号仅仅能是手机号或者邮箱等。我们还能够使用正則表達式来从一段字符串其中截取我们须要的字符串,比方说网页源代码中我们须要截取某些个图片地址等。总得来说。在iOS开发中正則表達式的作用有两点: 1. 检測给定的字符串是否符合业务逻辑 2. 从目标字符串中获取我们想要的特定字符串
How do I use the normal form in OC? 1. Using nspredicate (predicate) matching
NSString * targetString = @"13534341234"NSString * [email protected]"^[1][3578]+\\d{9}"; NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@"BOOLif (flag) { NSLog(@"是手机号码"); }else{ NSLog(@"不是手机号码"); }
如上代码所看到的为简单的正則表達式在iOS中的使用方式,意思为:用户输入的字符串是否为手机号码。 其中 `targetString` 为用书输入字符串,`regularExpression` 为正則表達式语法,`NSPredicate`为OC中查询过滤类
2. Using rangeofstring:option: Directly find the target string
NSString *string = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.hao123.com"] encoding:4 error:nil]; NSRange range = [string rangeOfString:@"()" options:NSRegularExpressionSearch];NSStringNSLog(@"subStr = %@",subStr);
如上代码就是从网页中过滤出我们的图片标签。删除结果为:``
3. Using the normal form class
NSString *string = [NSString Stringwithcontentsofurl:[nsurl urlwithstring:@ "http://www.hao123.com" ] Encoding : 4 error : nil ]; NSString *pattern = @ " "; Nsregularexpression *regex = [[nsregularexpression alloc] initwithpattern:pattern options: nsregularexpressioncaseinsensitive | Nsregularexpressiondotmatcheslineseparators Error:nil]; Nstextcheckingresult *checkresult = [regex firstmatchinstring:string options:nsmatchingreportcompletion Range: Nsmakerange (0, String.Length)]; NSString *result = [string Substringwithrange:[checkresult rangeatindex:0]] ; NSLog (@ "result =%@" , result);
This code is the same as the above code is found in the URL of a picture tag, then the URL of all the picture tags are found, how to write?
nsstring *string = [NSString stringwithcontentsofurl:[ Nsurl urlwithstring:@ "http://www.hao123.com" ] Encoding: 4 error : nil ]; NSString *pattern = @ " "; Nsregularexpression *regex = [[nsregularexpression alloc] initwithpattern:pattern options: nsregularexpressioncaseinsensitive | Nsregularexpressiondotmatcheslineseparators Error:nil]; Nsarray *thearray = [Regex matchesinstring:string options:nsmatchingreportprogress range:nsmakerange (0, String.Length )]; For (Nstextcheckingresult *ele in TheArray) {nsstring *thelaststring = [string Substringwithrange:[ele RangeA TINDEX:0]] ; NSLog (@ "thelaststring =%@" , thelaststring); }
So here's the problem. What's the ghost of a string like this?
NSString * [email protected]"^[1][3578*pattern = @"?)>";
Yes, that's our regular form. What about the syntax of the normal form? and listen to tell!
My Youku space, there is a video tutorial Oh, welcome to click.
iOS normal form (i)