欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-05-04 16:49:35
何谓正则表达式 正则表达式(regular expression),在计算机科学中,是指一个用来描述或者匹配一系列符合某个句法规则的字符串的单个字符串。在很多文本编辑...

何谓正则表达式

正则表达式(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输入的内容,希望大家喜欢。