侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

iOS中使用正则表达式NSRegularExpression 来验证textfiled输入的内容

苹果(mac/ios)  /  管理员 发布于 6年前   165

何谓正则表达式

正则表达式(regular expression),在计算机科学中,是指一个用来描述或者匹配一系列符合某个句法规则的字符串的单个字符串。在很多文本编辑器或其他工具里,正则表达式通常被用来检索和/或替换那些符合某个模式的文本内容。正则表达式这个概念最初是由Unix中的工具软件(例如sed和grep)普及开的。正则表达式通常缩写成“regex”,单数有regexp、regex,复数有regexps、regexes、regexen。

正则表达式组成

正则表达式有两种类型的字符组成

第一种:用来匹配的字符,或者叫常规字符

第二种:控制字符或具有特殊含义的元字符

iphone 4.0以后就开始支持正则表达式的使用了,在ios4.0中正则表达式的使用是使用NSRegularExpression类来调用。

1. 下面一个简单的使用正则表达式的一个例子:NSRegularExpression 类

-(void)parseString{//组装一个字符串,需要把里面的网址解析出来NSString *urlString=@"sfdsfhttp://www.baidu.com";//NSRegularExpression类里面调用表达的方法需要传递一个NSError的参数。下面定义一个 NSError *error;//http+:[^\\s]* 这个表达式是检测一个网址的。  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]; //等同于 firstMatch.range --- 相匹配的范围   //从urlString当中截取数据  NSString *result=[urlString substringWithRange:resultRange];  //输出结果  NSLog(@"%@",result);  }  }}

2.使用正则表达式来判断

//初始化一个NSRegularExpression 对象,并设置检测对象范围为:0-9 NSRegularExpression *regex2 = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]*$" options:0 error:nil];    if (regex2)    {//对象进行匹配       NSTextCheckingResult *result2 = [regex2 firstMatchInString:textField.text options:0 range:NSMakeRange(0, [textField.text length])];      if (result2) {      }}

1.判断邮箱格式是否正确的代码:NSPredicatel类

//利用正则表达式验证

NSPredicatel类:主要用来指定过滤器的条件,该对象可以准确的描述所需条件,对每个对象通过谓词进行筛选,判断是否与条件相匹配。谓词是指在计算机中表示计算真假值的函数。原理和用法都类似于SQL查询中的where,作用相当于数据库的过滤取。主要用于从集合中分拣出符合条件的对象,也可以用于字符串的正则匹配

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

2.匹配9-15个由字母/数字组成的字符串的正则表达式:

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

Cocoa用NSPredicate描述查询的方式,原理类似于在数据库中进行查询

用BETWEEN,IN,BEGINWITH,ENDWITH,CONTAINS,LIKE这些谓词来构造NSPredicate,必要的时候使用SELF直接对自己进行匹配

//基本的查询 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);     }   } //输出完整的信息   predicate = [NSPredicate predicateWithFormat: @"engine.horsepower > 150"];   NSArray *results;   results = [cars filteredArrayUsingPredicate: predicate];   NSLog (@"%@", results); //含有变量的谓词   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"); //注意不能使用$VARIABLE作为路径名,因为它值代表值 //谓词字符窜还支持c语言中一些常用的运算符   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);    }  }//输出完整的信息  predicate = [NSPredicate predicateWithFormat: @"engine.horsepower > 150"];  NSArray *results;  results = [cars filteredArrayUsingPredicate: predicate];  NSLog (@"%@", results);//含有变量的谓词  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");//注意不能使用$VARIABLE作为路径名,因为它值代表值//谓词字符窜还支持c语言中一些常用的运算符  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);

以上就是小编给大家分享的iOS中使用正则表达式NSRegularExpression 来验证textfiled输入的内容,希望大家喜欢。


  • 上一条:
    IOS开发常用的正则表达式
    下一条:
    正则表达式在IOS中的应用及IOS中三种正则表达式的使用与比较
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 苹果将在iOS 18中启用“苹果账户”名称,“Apple ID”将成历史(0个评论)
    • 2023年国内最新注册苹果开发者账号之申请邓白氏编码流程步骤(0个评论)
    • 2023年国内最新注册苹果个人开发者账号及支付会员年费流程步骤(0个评论)
    • 2022年3月2号最新免费的苹果美国id账号分享-美区Apple ID共享(0个评论)
    • Objective-C的%s和%@(1个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-11
    • 2018-11
    • 2022-01
    • 2023-02
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客