IOS _ Regular Expression

Source: Internet
Author: User

IOS _ Regular Expression
IOS Regular Expression

Regular Expression, also known as Regular Expression and Regular Expression (English: Regular Expression, often abbreviated as regex, regexp or RE in code), is a concept of computer science. Regular Expressions use a single string to describe and match a series of strings that conform to a certain syntax rule. In many text editors, regular expressions are usually used to retrieve and replace texts that match a certain pattern.

Built-in systems, such as NSPredicate, rangeOfString: option, and NSRegularExpression RegexKitLite are lightweight Objective-C Regular Expression Libraries that support Mac OS X and iOS and are developed using the ICU library.

AsRegexKitLite. This section focuses on the methods provided by the system.

PS: The premise is that you have mastered the basic regular expression syntax. If you are not familiar with the regular expression, you can refer to the following links:

Regular Expression learning link:

Learn Regular Expressions in 55 minutes uncover the mystery of Regular Expressions RegExLib.com (Regular Expression Library query) 1. NSPredicate

Brief description: NSPredicate in the Cocoa framework is used for queries. Its principles and usage are similar to where in SQL, and its function is equivalent to database filtering.

NSPredicate *predicate = [NSPredicate predicateWithFormat:(NSString *), ...];

Among them, the commonFormatInclude:

(1) Comparison operators: >,<,=, >=, <= ,! =

Example: @ "number> 100"

(2) range operators: IN,

Example: @ "number BETWEEN {}" @ "address IN {'shanghai', 'beijing '}"

(3) string itself: SELF

Example: @ "SELF = 'apple '"

(4) string correlation: BEGINSWITH, ENDSWITH, CONTAINS

Example: @ "name CONTAINS [cd] 'ang '" // CONTAINS a string @ "name BEGINSWITH [c] 'sh'" // starts with a string @ "name ENDSWITH [d] 'Ang '"// end with a string. Note: [c] case-insensitive [d] No pronunciation symbol, that is, no accent symbol [cd] is case-insensitive and does not distinguish pronunciation symbols.

(5) wildcard: LIKE

For example, @ "name LIKE [cd] '* er *'" // * Indicates a wildcard. Like also accepts [cd]. @ "name LIKE [cd] '??? Er *'"

(6) Regular Expression: MATCHES

For example, NSString * regex = @ "^ A. + e $"; // starts with A and ends with e @ "name MATCHES % @", regex

How to use it? The following are examples:

(A) filter NSArray and select items containing "ang ".

NSArray * array = [[NSArray alloc] initWithObjects: @ "beijing", @ "shanghai", @ "guangzou", @ "wuhan", nil]; NSString * string = @ "ang"; NSPredicate * pred = [NSPredicate predicateWithFormat: @ "self contains % @", string]; NSLog (@ "% @", [array filteredArrayUsingPredicate: pred]); // print the result: // (// shanghai, // guangzou //)

(B) filter NSDate

// Within ten days: NSDate * endDate = [NSDate date]; NSTimeInterval timeInterval = [endDate timeIntervalSinceReferenceDate]; timeInterval-= 3600*24*10; NSDate * beginDate = [NSDate dateWithTimeIntervalSinceReferenceDate: timeInterval]; // filter coredata (for example, fetchRequest) NSPredicate * predicate_date = [NSPredicate predicateWithFormat: @ "date >=% @ AND date <= % @", beginDate, endDate]; [fetchRequest setPredicate: predicate_date];

OK,NSPredicateIs also very powerful. This is the point for the time being. If you are interested, you can test them one by one. The following two examples illustrate how to use regular expressions.

// Determine whether the email is valid-(BOOL) isValidateEmail :( NSString *) email {NSString * regex = @ "[A-Z0-9a-z. _ % +-] + @ [A-Za-z0-9. -] + \\. [A-Za-z] {2, 4} "; NSPredicate * predicate = [NSPredicate predicateWithFormat: @" self matches % @ ", regex]; return [predicate evaluateWithObject: email] // determine whether the first letter of the string is the letter-(BOOL) isStartedWithWord :( NSString *) aString {NSString * regex = @ "[A-Za-z] + "; NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "self matches % @", regex]; return [predicate evaluateWithObject: aString];}
2. Use rangeOfString: option: to directly search
NSString * searchText = @ "// Do any additional setup after loading the view, typically from a nib."; nsange range = [searchText rangeOfString :@"(? : [^,]) * \. "Options: NSRegularExpressionSearch]; if (range. location! = NSNotFound) {NSLog (@ "% @", [searchText substringWithRange: range]);} // print the result: // typically from a nib.

NSRegularExpressionSearch is set in options to indicate that the position of the first matching result will be returned when regular expressions are used for matching.

3. Use Regular Expression classes

Learn more: iOS Regular Expression NSRegularExpression

The article above has a good summary. Here is a simple example:

NSString * searchText = @ "// Do any 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: 0 range: NSMakeRange (0, [searchText length])]; if (result) {NSLog (@ "% @ \ n", [searchText substringWithRange: result. range]);} // print the result: // typically from a nib.

Multiple matching results are returned using the system's regular expression class (NSRegularExpression.

Make a summary of the above three methods.

For the first match, you need to learn how to write NSPredicate, and you need to check the related technical documents of apple;

If you only care about the result of the first match, the second match is concise;

If you need to match multiple results multiple times at the same time, the third method is more efficient.

Common Regular Expressions

Reference: Common IOS Regular Expressions

Expression Function
[\ U4e00-\ u9fa5] Match Chinese Characters
[^ \ X00-\ xff] Match double-byte characters (including Chinese characters)
\ N \ s * \ r Match blank rows
<(\ S *?) [^>] *> .*? | <.*? /> Match HTML tags
^ \ S * | \ s * $ Match the first and last blank characters
\ W + ([-+.] \ w +) * @ \ w + ([-.] \ w + )*. \ w + ([-.] \ w + )* Match Email address
[A-zA-z] +: // [^ \ s] * Match URL
\ D {3}-\ d {8} | \ d {4}-\ d {7} Match a Chinese phone number, such as 0511-4405222 or 021-87888822
[1-9] \ d {5 }(?! \ D) Match China postal code
\ D +. \ d + Matching IP Address

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.