Filters and regular expressions (NSPredicate, NSRegularExpression) and nspredicate Regular Expressions in iOS

Source: Internet
Author: User

Filters and regular expressions (NSPredicate, NSRegularExpression) and nspredicate Regular Expressions in iOS

Reference: http://www.cocoachina.com/industry/20140321/8024.html

NSPredicate

Cocoa provides an NSPredicate class to specify filter conditions.

Initialization Method

+ (NSPredicate *) predicateWithFormat :( NSString *) predicateFormat ,...;

Format:

/**
1. format specifiers
Insert values and strings such as % d and % @. % K indicates the key.
You can also introduce the variable name. Use $, similar to the environment variable, for example, @ "NAME = $ name", and call predicateWithSubstitutionVariables to construct a new predicate (key/value dictionary ), the key is the variable name and the value is the content to be inserted. Note that in this case, the variable cannot be used as the key path, but only as the value.
2. Operators
 
= Equal
 
>: Greater
 
>=And ==>: greater than or equal
 
<: Less
 
<= And = <: less than or equal
 
! = And <>: not equal
 
Parentheses AND Equivalent Expressions of the logical operation AND, OR, NOT, or c Style &, | ,!
 
Note: The non-equal sign applies to numbers and strings.
 
 
3. array Operators
Add an array after BETWEEN and IN, you can use {50,200}, you can also use the % @ format to insert your own object, you can also use the variable
 
4. SELF is enough
Self indicates the object itself.
 
5. String Operators
BEGINSWITH: starts with a string
 
ENDSWITH: end with a string
 
CONTAINS: CONTAINS a string
@ "Name ENDSWITH [d] 'ang '"
 
[C], [d], [cd], and the suffix indicates not case sensitive, not pronunciation symbols.

6. LIKE Operator
 
LIKES similar to SQL
 
LIKE, and wildcard "*" indicates any number and "?" Indicates a combination
 
LIKE also accepts the [cd] symbol
 
7. MATCHES can use regular expressions.
NSString * regex = @ "^ A. + e $"; // starts with A and ends with e.
*/

 

Array category: Used to Filter Arrays

-(NSArray *) filteredArrayUsingPredicate :( NSPredicate *) predicate;

Variable Arrays can be directly filtered.

-(Void) filterUsingPredicate :( NSPredicate *) predicate;

For example, filter out the elements whose strings contain 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]);

Filter a single object

-(BOOL) evaluateWithObject :( id) object;

For example, determine whether the first letter in a string is a letter.

NSString * regex = @ "[A-Za-z] + ";
NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "self matches % @", regex];

If ([predicate evaluateWithObject: @ "hahaa"]) {
NSLog (@ "the first letter contains letters ");
} Else {
NSLog (@ "the first letter does not contain letters ");
}

Filter statement: Mailbox filter @ "[A-Z0-9a-z. _ % +-] + @ [A-Za-z0-9.-] + \. [A-Za-z }";

Phone number part: @ "^ 1 (3 [0-9] | 5 [0-35-9] | 8 [025-9]) \ d {8} $"

NSRegularExpression

String replacement

NSError * error = NULL;
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern: @ "(encoding = \") [^ \ "] + (\")"
Options: 0
Error: & error];
NSString * sample = @ "<xml encoding = \" abc \ "> </xml> <xml encoding = \" def \ "> </xml> <xml encoding = \" ttt \ "> </xml> ";
NSLog (@ "Start: % @", sample );
NSString * result = [regex stringByReplacingMatchesInString: sample
Options: 0
Range: NSMakeRange (0, sample. length)
WithTemplate: @ "$1utf-8 $2"];
NSLog (@ "Result: % @", result );

Truncates a string from a string.

// Assemble a string and parse the URL
NSString * urlString = @ "<meta/> <link/> <title> 1Q84 BOOK1 </title>
// The NSRegularExpression class must pass an NSError parameter to call the expression method. The following defines
NSError * error;

// Http +: [^ \ s] * This expression detects a URL. (? <= Title \> ).*(? = </Title) captures the regular expression of the text in <title> </title> in an html document.
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern :@"(? <= Title \> ).*(? = </Title) "options: 0 error: & error];

If (regex! = Nil ){
NSTextCheckingResult * firstMatch = [regex firstMatchInString: urlString options: 0 range: NSMakeRange (0, [urlString length])];

If (firstMatch ){
Nsange resultRange = [firstMatch rangeAtIndex: 0];

// Extract data from urlString
NSString * result = [urlString substringWithRange: resultRange];
// Output result
NSLog (@ "-> % @ <-", result );
}
}

NSPredicate test:

Define a class, assign values to the attribute when an accident occurs, use runtime to get all the attributes, and override the description method.

@ Interface DataModel: NSObject

@ Property (nonatomic, copy) NSString * name;
@ Property (nonatomic, assign) NSInteger num;

@ End # import "DataModel. h"
# Import <objc/runtime. h>

@ Implementation DataModel

-(Instancetype) init
{
Self = [super init];
If (self ){
Self. name = @ "haha ";
Self. num = 12;
}
Return self;
}

// Modify the description file (obtain all attributes and save them as dictionaries)
-(NSString *) description {
U_int count;
Objc_property_t * properties = class_copyPropertyList ([self class], & count );
NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
For (int I = 0; I <count; I ++)
{
Const char * propertyName = property_getName (properties [I]);
NSString * strName = [NSString stringWithCString: propertyName encoding: NSUTF8StringEncoding];
[Dic setObject: [self valueForKey: strName] forKey: strName];
}
Return [NSString stringWithFormat: @ "<% @ % p >:%@", self. class, & self, dic];
}

Example:

// (1) comparison operator >,<,=, >=, <= ,! =
-(Void) test1 {
DataModel * model = [[DataModel alloc] init];
// Inside the class
/*
Self. name = @ "haha ";
Self. num = 12;
*/
// Determines whether an attribute of a class is equal to a value and whether the string is equal.
NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "num> 11"];
BOOL match = [predicate evaluateWithObject: model];
NSLog (@ "% @", match? @ "Yes": @ "no ");
}


// Powerful array Filtering
-(Void) test2 {
NSMutableArray * mutableArray = [[NSMutableArray alloc] init];
DataModel * model1 = [[DataModel alloc] init];
DataModel * model2 = [[DataModel alloc] init];
DataModel * model3 = [[DataModel alloc] init];
Model2.num = 8;
Model3.name = @ "lala ";
[MutableArray addObject: model1];
[MutableArray addObject: model2];
[MutableArray addObject: model3];
NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "num> 10 AND name = 'lala"];
[MutableArray filterUsingPredicate: predicate];
NSLog (@ "filtered out: % @", mutableArray );
}

// The predicate containing the variable, which is used here> <will crash
-(Void) test3 {
DataModel * model = [[DataModel alloc] init];
NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "name = $ key"];
NSDictionary * dic =@{@ "key": @ "haha "};
NSPredicate * predicate1 = [predicate predicateWithSubstitutionVariables: dic];
NSLog (@ "% @", predicate1 );
BOOL match = [predicate1 evaluateWithObject: model];
NSLog (@ "% @", match? @ "Yes": @ "no ");
}

//
// Add an array after BETWEEN and IN. You can use {50,200} or the % @ format specifier to insert your own object or use a variable.
-(Void) test4 {
NSMutableArray * mutableArray = [[NSMutableArray alloc] init];
DataModel * model1 = [[DataModel alloc] init];
DataModel * model2 = [[DataModel alloc] init];
DataModel * model3 = [[DataModel alloc] init];
Model2.num = 8;
Model3.num = 20;
[MutableArray addObject: model1];
[MutableArray addObject: model2];
[MutableArray addObject: model3];

NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "num BETWEEN {5, 15}"];
[MutableArray filterUsingPredicate: predicate];
NSLog (@ "filtered out: % @", mutableArray );
}

// IN Operator

-(Void) test5 {

NSArray * arrayFilter = [NSArray arrayWithObjects: @ "abc1", @ "abc2", nil];

NSMutableArray * arrayContent = [NSMutableArray arrayWithObjects: @ "a1", @ "abc1", @ "abc4", @ "abc2", nil];

// Filter out the elements whose arrayContent does not contain arrayFilter.
NSPredicate * thePredicate = [NSPredicate predicateWithFormat: @ "NOT (SELF in % @)", arrayFilter];

[ArrayContent filterUsingPredicate: thePredicate];
NSLog (@ "% @", arrayContent );
}

// BEGINSWITH, ENDSWITH, CONTAINS
// LIKE operator (wildcard)
-(Void) test6 {
NSMutableArray * mutableArray = [[NSMutableArray alloc] init];
DataModel * model1 = [[DataModel alloc] init];
DataModel * model2 = [[DataModel alloc] init];
DataModel * model3 = [[DataModel alloc] init];
Model1.name = @ "a123.png ";
Model3.name = @ "a.png ";
[MutableArray addObject: model1];
[MutableArray addObject: model2];
[MutableArray addObject: model3];
NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "name LIKE [cd] 'a *. png '"];
[MutableArray filterUsingPredicate: predicate];
NSLog (@ "% @", mutableArray );
}

 

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.