天天看点

iOS小技能:NSPredicate在正则表达式的应用

引言

日常开发中,优雅高效的代码离不开Predicate的应用。

格式化字符串​​可以被看作三部分:左手表达式、逻辑符号和右手表达式。​​

其中,左手表达式是一个对象的属性键值(键路径);

逻辑符号是一个基本的逻辑运算符;

右手表达式是约束范围。

I 前置知识

Predicate Format String Syntax

1.1 Parser Basics

  • Two important format specifiers are %@ and %K.

%@ is a var arg substitution for an object value—often a string, number, or date.

%K is a var arg substitution for a key path.

NSString *attributeName  = @"firstName";
NSString *attributeValue = @"siting";
NSPredicate *predicate   = [NSPredicate predicateWithFormat:@"%K like %@",
        attributeName, attributeValue];      

1.2 Basic Comparisons

​=, ==​

​​The left-hand expression is equal to the right-hand expression.

​​

​>=, =>​

​​The left-hand expression is greater than or equal to the right-hand expression.

​​

​<=, =<​

​​The left-hand expression is less than or equal to the right-hand expression.

​​

​>​

​​The left-hand expression is greater than the right-hand expression.

​​

​<​

​​The left-hand expression is less than the right-hand expression.

​​

​!=, <>​

​The left-hand expression is not equal to the right-hand expression.

​BETWEEN​

The left-hand expression is between, or equal to either of, the values specified in the right-hand side.

The right-hand side is a two value array (an array is required to specify order) giving upper and lower bounds. For example, 1 BETWEEN { 0 , 33 }, or INPUT BETWEEN { LOWER, $UPPER }.

In Objective-C, you could create a BETWEEN predicate as shown in the following example:

NSPredicate *betweenPredicate =
    [NSPredicate predicateWithFormat: @"attributeName BETWEEN %@", @[@1, @10]];
NSDictionary *dictionary = @{ @"attributeName" : @5 };

BOOL between = [betweenPredicate eval(between) {
    NSLog(@"between");
}      

1.3 Basic Compound Predicates

​AND, &&​

​​Logical AND.

​​

​OR, ||​

​​Logical OR.

​​

​NOT, !​

​Logical NOT.

1.4 String Comparisons

逻辑运算符与SQL语句中的语法基本相对应,除了最基本的逻辑运算符之外,还有逻辑词IN、CONTAINS、like等。

它们的使用情况如下:

iOS小技能:NSPredicate在正则表达式的应用

​BEGINSWITH​

​​The left-hand expression begins with the right-hand expression.

​​

​CONTAINS​

​​The left-hand expression contains the right-hand expression.

​​

​ENDSWITH​

​​The left-hand expression ends with the right-hand expression.

​​

​LIKE​

The left hand expression equals the right-hand expression: ? and * are allowed as wildcard characters, where ? matches 1 character and * matches 0 or more characters.

MATCHES

The left hand expression equals the right hand expression using a regex-style comparison according to ICU v3 (for more details see the ICU User Guide for Regular Expressions).

UTI-CONFORMS-TO

The left hand argument to this operator is an expression that eval(UTI) you want to match.

The right hand argument is an expression that evaluates to a UTI.

The comparison eval(232, 232, 232); background: rgb(249, 249, 249);">

UTTypeConformsTo (A, B)      

When eval(of type NSExtensionItem), you could use a statement similar to the following:

SUBQUERY (
    extensionItems,
    $extensionItem,
    SUBQUERY (
        $extensionItem.attachments,
        $attachment,
        ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "com.adobe.pdf"
    ).@count == $extensionItem.attachments.@count
).@count == 1      

UTI-EQUALS

The left hand argument to this operator is an expression that eval(UTI) you want to match.

The right hand argument is an expression that evaluates to a UTI.

The comparison evaluates to TRUE if the UTI returned by the left hand expression equals the UTI returned by the right hand expression.

The clause A UTI-EQUALS B provides the same result as employing the UTTypeEqual method as follows:

UTTypeEqual (A, B)      

1.5 Aggregate Operations

ANY, SOME

Specifies any of the elements in the following expression. For example ANY children.age < 18.

ALL

Specifies all of the elements in the following expression. For example ALL children.age < 18.

NONE

Specifies none of the elements in the following expression. For example, NONE children.age < 18. This is logically equivalent to NOT (ANY ...).

IN

Equivalent to an SQL IN operation, the left-hand side must appear in the collection specified by the right-hand side.

For example, name IN { 'Ben', 'Melissa', 'Nick' }. The collection may be an array, a set, or a dictionary—in the case of a dictionary, its values are used.

In Objective-C, you could create a IN predicate as shown in the following example:

NSPredicate *inPredicate =
            [NSPredicate predicateWithFormat: @"attribute IN %@", aCollection];      
where aCollection may be an instance of NSArray, NSSet, NSDictionary, or of any of the corresponding mutable classes.

array[index]

Specifies the element at the specified index in the array array.

array[FIRST]

Specifies the first element in the array array.

array[LAST]

Specifies the last element in the array array.

array[SIZE]

Specifies the size of the array array.

1.6 Identifiers

C style identifier

Any C style identifier that is not a reserved word.

#symbol

Used to escape a reserved word into a user identifier.

​[\]{octaldigit}{3}​

Used to escape an octal number ( \ followed by 3 octal digits).

​[\][xX]{hexdigit}{2}​

Used to escape a hex number ( \x or \X followed by 2 hex digits).

​[\][uU]{hexdigit}{4}​

Used to escape a Unicode number ( \u or \U followed by 4 hex digits).

1.7 Literals

FALSE, NO

Logical false.

TRUE, YES

Logical true.

NULL, NIL

A null value.

SELF

Represents the object being eval(238, 238, 238); opacity: 0.6;">

A character string.

'text'

A character string.

Comma-separated literal array

For example, { 'comma', 'separated', 'literal', 'array' }.

Standard integer and fixed-point notations

For example, 1, 27, 2.71828, 19.75.

Floating-point notation with exponentiation

For example, 9.2e-5.

0x

Prefix used to denote a hexadecimal digit sequence.

0o

Prefix used to denote an octal digit sequence.

0b

Prefix used to denote a binary digit sequence.

1.8 Reserved Words

AND, OR, IN, NOT,

ALL, ANY, SOME, NONE,

LIKE, CASEINSENSITIVE, CI, MATCHES, CONTAINS, BEGINSWITH, ENDSWITH, BETWEEN,

NULL, NIL, SELF, TRUE, YES, FALSE, NO, FIRST, LAST, SIZE, ANYKEY, SUBQUERY, FETCH, CAST, TRUEPREDICATE, FALSEPREDICATE, UTI-CONFORMS-TO, UTI-EQUALS,

II NSPredicate在正则表达式的应用

2.1 商品分类名称

仅支持数字、字母、中文、斜杠\、横杠",且不能以符号开头

iOS小技能:NSPredicate在正则表达式的应用

“-”这个连接符需要转义-,否则报如下的错误

"Can't do regex matching, reason: Can't open pattern U_REGEX_MISSING_CLOSE_BRACKET (string U, pattern ^[0-9a-zA-Z一-龥][0-9a-zA-Z一-龥-\\]{0,}$, case 0, canon 0)"      

OC正确的写法:

​\\\​

​​表示斜杠​

​\​

​ 转义符

​\-​

​​代表横杆​

​-​

​ 连接符

BOOL)checkProductClassName: (NSString *) name
{
    NSString *pattern = @"^[0-9a-zA-Z\u4E00-\u9FA5][0-9a-zA-Z\u4E00-\u9FA5\\\\-]{0,}$";//
    NSLog(@"KN-pattern:%@",pattern);//2022-07-22 11:01:26.641648+0800 retail[5321:1883667] KN-pattern:^[0-9a-zA-Z一-龥][0-9a-zA-Z一-龥\\-]{0,}$

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred eval(232, 232, 232); background: rgb(249, 249, 249);">       
pattern: /^[0-9a-zA-Z\u4E00-\u9FA5][0-9a-zA-Z\u4E00-\u9FA5-\\]{0,}$/,      

2.2 基本校验例子

正则匹配用户密码6-16位数字和字母组合

BOOL)checkPassword:(NSString *) password
{
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,16}";

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];

    BOOL isMatch = [pred eval(232, 232, 232); background: rgb(249, 249, 249);">       
BOOL)checkTelNumber:(NSString *) telNumber
{
    NSString *pattern = @"^1+[3578]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred eval(BOOL)checkEmployeeNumber : (NSString *) number
{
    NSString *pattern = @"^[0-9]{12}";

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred eval(232, 232, 232); background: rgb(249, 249, 249);">       
BOOL)checkUserName : (NSString *) userName
{
    NSString *pattern = @"^[a-zA-Z\u4E00-\u9FA5]{1,20}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred eval(BOOL)checkUserIdCard: (NSString *) idCard
{
    NSString *pattern = @"(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred eval(232, 232, 232); background: rgb(249, 249, 249);">       
+ (BOOL)checkURL : (NSString *) url
{
    NSString *pattern = @"^[0-9A-Za-z]{1,50}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred eval(232, 232, 232); background: rgb(249, 249, 249);">       
+ (BOOL)isAmoutshouldChangeCharactersInRange:(NSString*)str{
    //匹配以0开头的数字
    NSPredicate * predicate0 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"^[0][0-9]+$"];
    //匹配两位小数、整数
    NSPredicate * predicate1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"^(([1-9]{1}[0-9]*|[0])\.?[0-9]{0,2})$"];
    return ![predicate0 eval(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{


        NSInteger len = range.length > 0?([textField.text length] - range.length): ([textField.text length] + [string length]);

        if(len > 20){
            return false;
        }
    ////
    NSString * str = [NSString stringWithFormat:@"%@%@",textField.text,string];

    return      

2.4 Url格式校验

+(BOOL)isUrl:(NSString *)url{
    NSString *regex =@"[a-zA-z]+://[^\\s]*";
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return      
  • 用法举例:自定义NSURLProtocol, 决定请求是否需要当前协议对象处理
/**
 决定请求是否需要当前协议对象处理

*/
+(BOOL)canInitWithRequest:(NSURLRequest *)request{

    if ([NSURLProtocol propertyForKey:protocolKey inRequest:request]) {
        return NO;
    }
    NSString * url = request.URL.absoluteString;
    return [self      

2.5 判断字符串是否为IP地址

/**
 * 判断字符串是否为IP地址
 * param iPAddress IP地址字符串
 * return BOOL 是返回YES,否返回NO
 */
+ (BOOL)isIPAddress:(NSString *)iPAddress{
    NSString *pattern = @"^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5]).(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5]).(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5]).(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$";
    return [self isText:iPAddress pattern:pattern];

}

+ (BOOL)isText:(NSString *)text pattern:(NSString *)pattern{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    return      

2.6 正则表达式的一些元字符

元字符 描述
\ 将下一个字符标记为一个特殊字符、或一个原义字符、或一个向后引用、或一个八进制转义符。例如,“\n”匹配\n。“\n”匹配换行符。序列“\”匹配“\”而“(”则匹配“(”。
匹配输入字符串的开始位置。如果设置了RegExp对象的Multiline属性,^也匹配“\n”或“\r”之后的位置。
$ 匹配输入字符串的结束位置。如果设置了RegExp对象的Multiline属性,$也匹配“\n”或“\r”之前的位置。
* 匹配前面的子表达式零次或多次(大于等于0次)。例如,zo*能匹配“z”,“zo”以及“zoo”。*等价于{0,}。
+ 匹配前面的子表达式一次或多次(大于等于1次)。例如,“zo+”能匹配“zo”以及“zoo”,但不能匹配“z”。+等价于{1,}。
? 匹配前面的子表达式零次或一次。例如,“do(es)?”可以匹配“do”或“does”中的“do”。?等价于{0,1}。
{n} n是一个非负整数。匹配确定的n次。例如,“o{2}”不能匹配“Bob”中的“o”,但是能匹配“food”中的两个o。
{n,} n是一个非负整数。至少匹配n次。例如,“o{2,}”不能匹配“Bob”中的“o”,但能匹配“foooood”中的所有o。“o{1,}”等价于“o+”。“o{0,}”则等价于“o*”。
{n,m} m和n均为非负整数,其中n<=m。最少匹配n次且最多匹配m次。例如,“o{1,3}”将匹配“fooooood”中的前三个o。“o{0,1}”等价于“o?”。请注意在逗号和两个数之间不能有空格。
? 当该字符紧跟在任何一个其他限制符(*,+,?,{n},{n,},{n,m})后面时,匹配模式是非贪婪的。非贪婪模式尽可能少的匹配所搜索的字符串,而默认的贪婪模式则尽可能多的匹配所搜索的字符串。例如,对于字符串“oooo”,“o+?”将匹配单个“o”,而“o+”将匹配所有“o”。
.点 匹配除“\r\n”之外的任何单个字符。要匹配包括“\r\n”在内的任何字符,请使用像“[\s\S]”的模式。
(pattern) 匹配pattern并获取这一匹配。所获取的匹配可以从产生的Matches集合得到,在VBScript中使用SubMatches集合,在JScript中则使用9属性。要匹配圆括号字符,请使用“(”或“)”。
(?:pattern) 匹配pattern但不获取匹配结果,也就是说这是一个非获取匹配,不进行存储供以后使用。这在使用或字符“(|)”来组合一个模式的各个部分是很有用。例如“industr(?:y|ies)”就是一个比“industry|industries”更简略的表达式。
(?=pattern) 正向肯定预查,在任何匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如,“Windows(?=95|98|NT|2000)”能匹配“Windows2000”中的“Windows”,但不能匹配“Windows3.1”中的“Windows”。预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始。
(?!pattern) 正向否定预查,在任何不匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如“Windows(?!95|98|NT|2000)”能匹配“Windows3.1”中的“Windows”,但不能匹配“Windows2000”中的“Windows”。
(?<=pattern) 反向肯定预查,与正向肯定预查类似,只是方向相反。例如,“(?<=95|98|NT|2000)Windows”能匹配“2000Windows”中的“Windows”,但不能匹配“3.1Windows”中的“Windows”。
(?<!pattern) 反向否定预查,与正向否定预查类似,只是方向相反。例如“(?<!95|98|NT|2000)Windows”能匹配“3.1Windows”中的“Windows”,但不能匹配“2000Windows”中的“Windows”。
x|y 匹配x或y。例如,“z|food”能匹配“z”或“food”。“(z|f)ood”则匹配“zood”或“food”。
[xyz] 字符集合。匹配所包含的任意一个字符。例如,“[abc]”可以匹配“plain”中的“a”。
[^xyz] 负值字符集合。匹配未包含的任意字符。例如,“[^abc]”可以匹配“plain”中的“plin”。
[a-z] 字符范围。匹配指定范围内的任意字符。例如,“[a-z]”可以匹配“a”到“z”范围内的任意小写字母字符。注意:只有连字符在字符组内部时,并且出现在两个字符之间时,才能表示字符的范围; 如果出字符组的开头,则只能表示连字符本身.
[^a-z] 负值字符范围。匹配任何不在指定范围内的任意字符。例如,“[^a-z]”可以匹配任何不在“a”到“z”范围内的任意字符。
\b 匹配一个单词边界,也就是指单词和空格间的位置。例如,“er\b”可以匹配“never”中的“er”,但不能匹配“verb”中的“er”。
\B 匹配非单词边界。“er\B”能匹配“verb”中的“er”,但不能匹配“never”中的“er”。
\cx 匹配由x指明的控制字符。例如,\cM匹配一个Control-M或回车符。x的值必须为A-Z或a-z之一。否则,将c视为一个原义的“c”字符。
\d 匹配一个数字字符。等价于[0-9]。
\D 匹配一个非数字字符。等价于[^0-9]。
\f 匹配一个换页符。等价于\x0c和\cL。
\n 匹配一个换行符。等价于\x0a和\cJ。
\r 匹配一个回车符。等价于\x0d和\cM。
\s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于[ \f\n\r\t\v]。
\S 匹配任何非空白字符。等价于[^ \f\n\r\t\v]。
\t 匹配一个制表符。等价于\x09和\cI。
\v 匹配一个垂直制表符。等价于\x0b和\cK。
\w 匹配包括下划线的任何单词字符。等价于“[A-Za-z0-9_]”。
\W 匹配任何非单词字符。等价于“[^A-Za-z0-9_]”。
\xn 匹配n,其中n为十六进制转义值。十六进制转义值必须为确定的两个数字长。例如,“\x41”匹配“A”。“\x041”则等价于“\x04&1”。正则表达式中可以使用ASCII编码。
\num 匹配num,其中num是一个正整数。对所获取的匹配的引用。例如,“(.)\1”匹配两个连续的相同字符。
\n 标识一个八进制转义值或一个向后引用。如果\n之前至少n个获取的子表达式,则n为向后引用。否则,如果n为八进制数字(0-7),则n为一个八进制转义值。
\nm 标识一个八进制转义值或一个向后引用。如果\nm之前至少有nm个获得子表达式,则nm为向后引用。如果\nm之前至少有n个获取,则n为一个后跟文字m的向后引用。如果前面的条件都不满足,若n和m均为八进制数字(0-7),则\nm将匹配八进制转义值nm。
\nml 如果n为八进制数字(0-7),且m和l均为八进制数字(0-7),则匹配八进制转义值nml。
\un 匹配n,其中n是一个用四个十六进制数字表示的Unicode字符。例如,\u00A9匹配版权符号(©)。
< > 匹配词(word)的开始(<)和结束(>)。例如正则表达式<the>能够匹配字符串"for the wise"中的"the",但是不能匹配字符串"otherwise"中的"the"。注意:这个元字符不是所有的软件都支持的。
( ) 将 ( 和 ) 之间的表达式定义为“组”(group),并且将匹配这个表达式的字符保存到一个临时区域(一个正则表达式中最多可以保存9个),它们可以用 \1 到\9 的符号来引用。
| 将两个匹配条件进行逻辑“或”(Or)运算。例如正则表达式(him|her) 匹配"it belongs to him"和"it belongs to her",但是不能匹配"it belongs to them."。注意:这个元字符不是所有的软件都支持的。
+ 匹配1或多个正好在它之前的那个字符。例如正则表达式9+匹配9、99、999等。注意:这个元字符不是所有的软件都支持的。
? 匹配0或1个正好在它之前的那个字符。注意:这个元字符不是所有的软件都支持的。
{i} {i,j} 匹配指定数目的字符,这些字符是在它之前的表达式定义的。例如正则表达式A[0-9]{3} 能够匹配字符"A"后面跟着正好3个数字字符的串,例如A123、A348等,但是不匹配A1234。而正则表达式[0-9]{4,6} 匹配连续的任意4个、5个或者6个数字

III 从数组搜索特定条件的元素

从数组中筛选type=8的电子签名数据,避免遍历数组 certificateInfoList

————————————————

版权声明:本文为博主「#公众号:iOS逆向」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

iOS小技能:NSPredicate在正则表达式的应用

see also

公众号:iOS逆向

  • 打赏
  • 收藏
  • 评论
  • 分享
  • 举报

上一篇:iOS小技能:设备ID除了使用_idfa、_idfv 还可使用其他替代方案(使用Keychain 存储UUID)

下一篇:iOS小技能:参数名ASCII码从小到大排序、对象数组排序

举报文章

请选择举报类型

内容侵权

涉嫌营销

内容抄袭

违法信息

其他

具体原因

包含不真实信息

涉及个人隐私

原文链接(必填)

补充说明

取消

确认

已经收到您得举报信息,我们会尽快审核

iOS小技能:NSPredicate在正则表达式的应用

提问和评论都可以,用心的回复会被更多人看到

评论

发布评论

全部评论

(

)

最热

最新

{{value.nickname}}

{{if value.is_author == 1}}

博主

{{/if}}

{{value.create_time}}

{{value.content}}

{{if value.is_reply == 1}}

回复

{{/if}}

点赞

{{value.up_num>0 ? value.up_num : ''}}

{{if value.is_delete == 1}}

删除

{{/if}}

{{if value.children.total > 0}}

{{each value.children.list item key}}

3}}style="display:none;"{{/if}}>

iOS小技能:NSPredicate在正则表达式的应用

{{if item.is_vip == 1}}

{{/if}}

{{item.nickname}}

{{if item.is_author == 1}}

博主

{{/if}}

回复了

{{item.reply_nickname}} {{item.create_time}}

{{if item.is_reply_content>0}}

{{item.reply_content}}

{{/if}}

{{item.content}}

{{if item.is_reply == 1}}

回复

{{/if}}

点赞

{{item.up_num>0 ? item.up_num : ''}}

{{if item.is_delete == 1}}

删除

{{/if}}

{{if key == 3}}

查看更多回复

{{/if}}

{{/each}}

{{/if}}