IOS Regular Expressions
Regular expressions, also known as formal notation, conventional notation (English: Regular expression, often abbreviated in code as regex, RegExp, or re), is a concept of computer science. A regular expression uses a single string to describe and match a series of strings that conform to a certain syntactic rule. In many text editors, regular expressions are often used to retrieve and replace text that conforms to a pattern.
- System comes with, such as: Nspredicate, Rangeofstring:option, nsregularexpression
- Regexkitlite Regexkitlite is a lightweight objective-c regular expression library that supports Mac OS X and IOS and is developed using the ICU library.
As RegexKitLite for, there is no introduction here. Focus on the system comes with the several methods.
PS: Read the premise of this article is that you have mastered the regular basic syntax, if you are not familiar with the regular, you can refer to the following links:
Regular Expression Learning Links:
- 55-minute learning regular expression
- Uncover the mystery of regular expressions
- Regexlib.com (regular expression library query)
1. Nspredicate
Description: The nspredicate in the cocoa Framework is used for querying, both in principle and in usage similar to where in SQL, which acts as a filter for the database.
...];
Among them, the common ones Format are:
(1) comparison operator:;, <, = =, >=, <=,! =
例:@"number > 100"
(2) Scope operator: in, between
例:@"number BETWEEN {1,5}" @"address IN {‘shanghai‘,‘beijing‘}"
(3) string itself: Self
例:@“SELF == ‘APPLE’"
(4) String correlation: Beginswith, ENDSWITH, CONTAINS
例:@"name CONTAINS[cd] ‘ang‘" //包含某个字符串 @"name BEGINSWITH[c] ‘sh‘" //以某个字符串开头 @"name ENDSWITH[d] ‘ang‘" //以某个字符串结束注:[c]不区分大小写 [d]不区分发音符号即没有重音符号 [cd]既不区分大小写,也不区分发音符号。
(5) wildcard character: like
例:@"name LIKE[cd] ‘*er*‘" //*代表通配符,Like也接受[cd]. @"name LIKE[cd] ‘???er*‘"
(6) Regular expression: MATCHES
例:NSString *regex = @"^A.+e$"; //以A开头,e结尾 @"name MATCHES %@",regex
As for how to use it? Here are a few examples:
(a) filtering the Nsarray and selecting items containing "Ang"
NSArray *array = [[nsarray alloc]initwithobjects:@ "Beijing" , @, @ "Guangzou" , @ "Wuhan" , nil ]; nsstring *string = @ "Ang" ; Nspredicate *pred = [nspredicate predicatewithformat:@ "self CONTAINS%@" , string]; nslog (@ "%@" , [array filteredarrayusingpredicate:pred]); //print Result: //( //Shanghai, // Guangzou //)
(b) Screening of NSDate
//日期在十天之内: NSDate *endDate = [NSDate date]; NSTimeInterval timeInterval= [endDate timeIntervalSinceReferenceDate]; timeInterval -=3600*24*10; NSDate *beginDate = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval]; //对coredata进行筛选(假设有fetchRequest) NSPredicate *predicate_date = [NSPredicate predicateWithFormat:@"date >= %@ AND date <= %@", beginDate,endDate]; [fetchRequest setPredicate:predicate_date];
OK, a NSPredicate lot of features, but also very powerful. Here for the time being here, the interested can be tested on their own. Here are two examples of how to use the regular.
//Determine if it is a valid mailbox- (BOOL) Isvalidateemail: (NSString*) email{NSString*regex = @"[A-z0-9a-z._%+-][email protected][a-za-z0-9.-]+\\. [A-za-z] {2,4} "; Nspredicate *predicate = [Nspredicate predicatewithformat:@"Self MATCHES%@", regex];return[Predicate evaluatewithobject:email];}//Determine if the first letter of the string is a letter- (BOOL) Isstartedwithword: (NSString*) astring{NSString*regex = @"[a-za-z]+]; Nspredicate *predicate = [Nspredicate predicatewithformat:@"Self MATCHES%@", regex];return[Predicate evaluatewithobject:astring];}
2. Using rangeofstring:option: Direct lookup
NSString *searchText = @"// Do any additional setup after loading the view, typically from a nib."; NSRange range = [searchText rangeOfString:@"(?:[^,])*\\." options:NSRegularExpressionSearch]; if (range.locationNSNotFound) { NSLog(@"%@", [searchText substringWithRange:range]); }// 打印结果:// typically from a nib.
The set nsregularexpressionsearch in options means that a regular expression match is used to return the position of the first matching result.
3. Using the Regular expression class
Learn more: IOS Regular expression Nsregularexpression
The above article summarizes very well. Here's a quick example:
NSString*searchtext = @additional setup after loading the view, typically from a nib. ";Nserror*error =NULL; Nsregularexpression *regex = [Nsregularexpression regularexpressionwithpattern:@"(?:[^,])*\\."Options:nsregularexpressioncaseinsensitive error:&error]; Nstextcheckingresult *result = [Regex firstmatchinstring:searchtext options:0Range:nsmakerange (0, [SearchText length])];if(Result) {NSLog(@"%@\n", [SearchText Substringwithrange:result. Range]); }//Printing results://typically from a nib.
Using the system's regular expression class (Nsregularexpression) returns multiple results that match.
For the above 3 ways, make a small summary
The first kind of match needs to learn the nspredicate, need to consult Apple related technical documents;
If you only care about the results of the first match, the second match is more concise;
If you need to match multiple results and match them multiple times, the third way is more efficient.
Common Regular Expressions
Reference: iOS common regular expressions
| An expression |
function |
| [\u4e00-\u9fa5] |
Match Chinese characters |
| [^\x00-\xff] |
Match double-byte characters (including kanji) |
| \n\s*\r |
Match Blank Lines |
| < (\s*?) [^>]*>.*?| <.*? /> |
Matching HTML tags |
| ^\s*|\s*$ |
Match the trailing white space character |
| \w+ ([-+.] \w+) *@\w+ ([-.] \w+) *.\w+ ([-.] \w+) * |
Match email to |
| [a-za-z]+://[^\s]* |
Match URL URLs |
| \D{3}-\D{8}|\D{4}-\D{7} |
Match domestic phone number, match form such as 0511-4405222 or 021-87888822 |
| [1-9]\d{5} (?! \d) |
Match China postcode |
| \d+.\d+.\d+.\d+ |
Match IP Address |
Ios_ Regular Expressions