天天看点

iOS中系统自带正则表达式的应用

//组装一个字符串,把里面的网址解析出来

nsstring *urlstring = @"sfdshttp://www.baidu.com";

nserror *error;

//http+:[^\\s]* 这是检测网址的正则表达式

nsregularexpression *regex = [nsregularexpression regularexpressionwithpattern:@"http+:[^\\s]*" options:0 error:&error];

if (regex != nil) {

nstextcheckingresult *firstmatch = [regex firstmatchinstring:urlstring options:0 range:nsmakerange(0, [urlstring length])];

if (firstmatch) {

nsrange resultrange = [firstmatch rangeatindex:0];

//从urlstring中截取数据

nsstring *result = [urlstring substringwithrange:resultrange];

nslog(@"%@",result);

}

  输出结果为:

  [1302:403] http://www.baidu.com

  可见通过ios自带的正则表达式的类可以达到过滤和筛选字符串的功能。

  还有其他两种正则表达式的用法:

  1.利用nspredicate(谓词)匹配

  例如匹配有效邮箱:

  nsstring *email = @“[email protected]”;

  nsstring *regex = @"[a-z0-9a-z._%+-]+@[a-za-z0-9.-]+\\.[a-za-z]{2,4}";

  nspredicate *predicate = [nspredicate predicatewithformat:@"self matches %@", regex];

  bool isvalid = [predicate evaluatewithobject:email];

  谓词匹配比较灵活,但是需要有谓词的相关知识。

  2.利用rangeofstring:option:直接查找

  nsstring *searchtext = @"// do any additional setup after loading the view, typically from a nib.";

  nsrange range = [searchtext rangeofstring:@"(?:[^,])*\\." options:nsregularexpressionsearch];

  if (range.location != nsnotfound) {

  nslog(@"%@", [searchtext substringwithrange:range]);

  }

  options中设定nsregularexpressionsearch就是表示利用正则表达式匹配,会返回第一个匹配结果的位置。

  小结:

最新内容请见作者的github页:http://qaseven.github.io/