Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use regular expression NSRegularExpression in iOS to validate textfiled input

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces iOS how to use the regular expression NSRegularExpression to verify the content of textfiled input, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

What is a regular expression?

Regular expression (regular expression), in computer science, is a single string used to describe or match a series of strings that conform to a syntactic rule. In many text editors or other tools, regular expressions are often used to retrieve and / or replace text content that matches a pattern. The concept of regular expressions was first popularized by tools in Unix, such as sed and grep. Regular expressions are usually abbreviated to "regex". The singular has regexp and regex, and the plural has regexps, regexes, and regexen.

Regular expression composition

Regular expressions are made up of two types of characters

The first: characters used to match, or regular characters.

The second kind: control characters or metacharacters with special meaning

The use of regular expressions has been supported since iphone 4.0.In ios4.0, regular expressions are called using the NSRegularExpression class.

1. The following is a simple example of using regular expressions: the NSRegularExpression class

-(void) parseString {/ / assembles a string, which needs to parse the URL into the NSString * urlString=@ "sfdsf http://www.baidu.com";//NSRegularExpression class. The method expressed in the call needs to pass a parameter of NSError. The following defines a NSError * error;//http+: [^\\ s] * this expression detects a URL. NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:@ "http+: [^\\ s] *" options:0 error:&error]; if (regex! = nil) {NSTextCheckingResult * firstMatch= [regex firstMatchInString:urlString options:0range:NSMakeRange (0, [urlString length])]; if (firstMatch) {NSRange resultRange = [firstMatch rangeAtIndex:0]; / equivalent to firstMatch.range-- matching range / / intercepting data NSString * result= [urlString substringWithRange:resultRange] from urlString / / output result NSLog (@ "% @", result);}

two。 Use regular expressions to judge

/ / initialize a NSRegularExpression object and set the detection object range to: 0-9 NSRegularExpression * regex2 = [NSRegularExpression regularExpressionWithPattern:@ "^ [0-9] * $" options:0 error:nil]; if (regex2) {/ / object matching NSTextCheckingResult * result2 = [regex2 firstMatchInString:textField.text options:0 range:NSMakeRange (0, [textField.text length])]; if (result2) {}}

1. The code to determine whether the mailbox is in the correct format: NSPredicatel class

/ / validate using regular expressions

NSPredicatel class: mainly used to specify the conditions of the filter, this object can accurately describe the required conditions, filter each object through the predicate to determine whether it matches the condition. A predicate is a function that represents a true or false value in a computer. The principle and usage are similar to where in SQL query, which is equivalent to the filtering of database. It is mainly used to sort qualified objects from the collection, and it can also be used for regular matching of strings.

-(BOOL) isValidateEmail: (NSString *) email {NSString * emailRegex = @ "[A-Z0-9a murz.conversation% stories -] + @ [A-Za-z0-9.-] +\. [A-Za-z] {2jue 4}"; NSPredicate * emailTest = [NSPredicate predicateWithFormat:@ "SELF MATCHES%@", emailRegex]; return [emailTest evaluateWithObject:email];}

two。 A regular expression that matches 9-15 alphanumeric strings:

NSString * regex = @ "^ [A-Za-z0-9] {9 NSPredicate 15} $"; NSPredicate * pred = [NSPredicate predicateWithFormat:@ "SELF MATCHES% @", regex]; BOOL isMatch = [pred evaluateWithObject:txtfldPhoneNumber.text]

Cocoa uses NSPredicate to describe the query, which is similar to querying in a database.

Use BETWEEN,IN,BEGINWITH,ENDWITH,CONTAINS,LIKE predicates to construct NSPredicate and, if necessary, use SELF to match yourself directly.

/ / basic query NSPredicate * predicate; predicate = [NSPredicate predicateWithFormat: @ "name = = 'Herbie'"]; BOOL match = [predicate evaluateWithObject: car]; NSLog (@ "% s", (match)? "YES": "NO"); / / cycle through cars to compare predicate = [NSPredicate predicateWithFormat: @ "engine.horsepower > 150"]; NSArray * cars = [garage cars]; for (Car * car in [garage cars]) {if ([predicate evaluateWithObject: car]) {NSLog (@"% @ ", car.name);}} / / output complete information predicate = [NSPredicate predicateWithFormat: @" engine.horsepower > 150"] NSArray * results; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@ "% @", results); / / predicates with variables NSPredicate * predicateTemplate = [NSPredicate predicateWithFormat:@ "name = = $NAME"]; NSDictionary * varDict; varDict = [NSDictionary dictionaryWithObjectsAndKeys: @ "Herbie", @ "NAME", nil]; predicate = [predicateTemplate predicateWithSubstitutionVariables: varDict]; NSLog (@ "SNORGLE:% @", predicate); match = [predicate evaluateWithObject: car] NSLog (@ "% s", (match)? "YES": "NO"); / / Note that $VARIABLE cannot be used as the pathname, because its value represents value / / predicate character channeling and supports some common operators in c language predicate = [NSPredicate predicateWithFormat: @ "(engine.horsepower > 50) AND (engine.horsepower)

< 200)"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@"oop %@", results); predicate = [NSPredicate predicateWithFormat: @"name < 'Newton'"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@"%@", [results valueForKey: @"name"]); //强大的数组运算符 predicate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN { 50, 200 }"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@"%@", results); NSArray *betweens = [NSArray arrayWithObjects: [NSNumber numberWithInt: 50], [NSNumber numberWithInt: 200], nil]; predicate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN %@", betweens]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@"%@", results); predicateTemplate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN $POWERS"]; varDict = [NSDictionary dictionaryWithObjectsAndKeys: betweens, @"POWERS", nil]; predicate = [predicateTemplate predicateWithSubstitutionVariables: varDict]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@"%@", results); //IN运算符 predicate = [NSPredicate predicateWithFormat: @"name IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@"%@", [results valueForKey: @"name"]); predicate = [NSPredicate predicateWithFormat: @"SELF.name IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@"%@", [results valueForKey: @"name"]); names = [cars valueForKey: @"name"]; predicate = [NSPredicate predicateWithFormat: @"SELF IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"]; results = [names filteredArrayUsingPredicate: predicate];//这里限制了SELF的范围 NSLog (@"%@", results); //BEGINSWITH,ENDSWITH,CONTAINS //附加符号,[c],[d],[cd],c表示不区分大小写,d表示不区分发音字符,cd表示什么都不区分 predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH 'Bad'"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@"%@", results); predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH 'HERB'"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@"%@", results); predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH[cd] 'HERB'"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@"%@", results); //LIKE运算符(通配符) predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] '*er*'"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@"%@", results); predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] '???er*'"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@"%@", results); //基本的查询NSPredicate *predicate;predicate = [NSPredicate predicateWithFormat: @"name == 'Herbie'"]; BOOL match = [predicate evaluateWithObject: car]; NSLog (@"%s", (match) ? "YES" : "NO");//在整个cars里面循环比较 predicate = [NSPredicate predicateWithFormat: @"engine.horsepower >

150 "]; NSArray * cars = [garage cars]; for (Car * car in [garage cars]) {if ([predicate evaluateWithObject: car]) {NSLog (@"% @ ", car.name);}} / / output complete information predicate = [NSPredicate predicateWithFormat: @" engine.horsepower > 150 "]; NSArray * results; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@"% @ ", results) / / predicate NSPredicate * predicateTemplate = [NSPredicate predicateWithFormat:@ "name = = $NAME"]; NSDictionary * varDict; varDict = [NSDictionary dictionaryWithObjectsAndKeys: @ "Herbie", @ "NAME", nil]; predicate = [predicateTemplate predicateWithSubstitutionVariables: varDict]; NSLog (@ "SNORGLE:% @", predicate); match = [predicate evaluateWithObject: car]; NSLog (@ "% s", (match)? "YES": "NO"); / / Note that $VARIABLE cannot be used as the pathname, because its value represents the value / / predicate character channeling and supports some commonly used operators in c language predicate = [NSPredicate predicateWithFormat: @ "(engine.horsepower > 50) AND (engine.horsepower < 200)]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@" oop% @ ", results); predicate = [NSPredicate predicateWithFormat: @" name < 'Newton' "] Results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@ "% @", [results valueForKey: @ "name"]); / / powerful array operator predicate = [NSPredicate predicateWithFormat: @ "engine.horsepower BETWEEN {50200}"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@ "% @", results); NSArray * betweens = [NSArray arrayWithObjects: [NSNumber numberWithInt: 50], [NSNumber numberWithInt: 200], nil] Predicate = [NSPredicate predicateWithFormat: @ "engine.horsepower BETWEEN% @", betweens]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@ "% @", results); predicateTemplate = [NSPredicate predicateWithFormat: @ "engine.horsepower BETWEEN $POWERS"]; varDict = [NSDictionary dictionaryWithObjectsAndKeys: betweens, @ "POWERS", nil]; predicate = [predicateTemplate predicateWithSubstitutionVariables: varDict]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@ "% @", results) / / IN operator predicate = [NSPredicate predicateWithFormat: @ "name IN {'Herbie',' Snugs', 'Badger',' Flap'}"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@ "% @", [results valueForKey: @ "name"]); predicate = [NSPredicate predicateWithFormat: @ "SELF.name IN {'Herbie',' Snugs', 'Badger',' Flap'}"]; results = [cars filteredArrayUsingPredicate: predicate] NSLog (@ "% @", [results valueForKey: @ "name"]); names = [cars valueForKey: @ "name"]; predicate = [NSPredicate predicateWithFormat: @ "SELF IN {'Herbie',' Snugs', 'Badger',' Flap'}"]; results = [names filteredArrayUsingPredicate: predicate]; / / the scope of SELF is restricted NSLog (@ "% @", results) / BEGINSWITH,ENDSWITH,CONTAINS// additional symbols, [c], [d], [cd], c means case-insensitive, d means case-insensitive, cd means predicate = [NSPredicate predicateWithFormat: @ "name BEGINSWITH 'Bad'"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@ "% @", results); predicate = [NSPredicate predicateWithFormat: @ "name BEGINSWITH' HERB'"]; results = [cars filteredArrayUsingPredicate: predicate] NSLog (@ "% @", results); predicate = [NSPredicate predicateWithFormat: @ "name BEGINSWITH [cd] 'HERB'"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@ "% @", results); / / LIKE operator (wildcard) predicate = [NSPredicate predicateWithFormat: @ "name LIKE [cd]' * er*'"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@ "% @", results) Predicate = [NSPredicate predicateWithFormat: @ "name LIKE [cd]'? er*'"]; results = [cars filteredArrayUsingPredicate: predicate]; NSLog (@ "% @", results) Thank you for reading this article carefully. I hope the article "how to use regular expression NSRegularExpression to verify the input of textfiled in iOS" shared by the editor is helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report