NSPredicate和正则表达式 [英] NSPredicate and Regex

查看:321
本文介绍了NSPredicate和正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我将Regex与NSPredicate一起使用吗?

Can someone please help me with using Regex with NSPredicate?

NSString *regex = @"(?:[A-Za-z0-9])";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
if ([pred evaluateWithObject:mystring])
{
  //do something
}

测试上面的mystring-qstring123似乎不起作用.我期望它进入if条件,因为它应该与正则表达式匹配.

testing the above wth mystring - qstring123 doesn't seem to work. I am expecting it to enter the if condition because it supposedly should match the regex.

此外,我需要一个用于字母数字的正则表达式,以允许使用逗号和空格.

Besides, I need a regex for alpha numberic allowing commas and spaces.

这行得通吗?

@"(?:[A-Za-z0-9])*(?:,[A-sa-z0-9)*(?:\s[A-sa-s0-9])"

请帮助.

推荐答案

根据我的实验,它尝试将正则表达式与整个字符串匹配,而在字符串内部不匹配.

From my experimentation, it tries to match the regex against the entire string, and won't match inside a string.

因此,正则表达式[a-zA-Z0-9]+有效,但[a-zA-Z0-9]无效.

Therefore, the regex [a-zA-Z0-9]+ works, but [a-zA-Z0-9] does not.

考虑到这一点,您可能需要重新处理逗号匹配谓词,或者使用功能更全的正则表达式解决方案,例如令人惊叹的 RegexKit和RegexKitLite .

With that in mind, you may want to rework your comma-matching predicate, or use a more full-featured regex solution, like the amazingly awesome RegexKit and RegexKitLite.

这篇关于NSPredicate和正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆