前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS小技能:NSPredicate在正则表达式的应用

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

作者头像
公众号iOS逆向
发布2022-08-22 11:48:15
8520
发布2022-08-22 11:48:15
举报
文章被收录于专栏:iOS逆向与安全

引言

日常开发中,优雅高效的代码离不开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.

代码语言:javascript
复制
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:

代码语言:javascript
复制
NSPredicate *betweenPredicate =
    [NSPredicate predicateWithFormat: @"attributeName BETWEEN %@", @[@1, @10]];
NSDictionary *dictionary = @{ @"attributeName" : @5 };
 
BOOL between = [betweenPredicate evaluateWithObject:dictionary];
if (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等。它们的使用情况如下:

BEGINSWITHThe left-hand expression begins with the right-hand expression.CONTAINSThe left-hand expression contains the right-hand expression.ENDSWITHThe 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 evaluates to a universal type identifier (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 conforms to the UTI returned by the right hand expression. For information on which types conform to a given type, see System-Declared Uniform Type Identifiers in Uniform Type Identifiers Reference.

The clause A UTI-CONFORMS-TO B provides the same result as employing the UTTypeConformsTo method as follows:

代码语言:javascript
复制
UTTypeConformsTo (A, B)

When evaluating attachments in an app extension item (of type NSExtensionItem), you could use a statement similar to the following:

代码语言:javascript
复制
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 evaluates to a universal type identifier (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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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 evaluated.

"text"

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 商品分类名称

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

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

代码语言:javascript
复制
 thread 1: "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正确的写法:\\\表示斜杠\ 转义符

\-代表横杆- 连接符

代码语言:javascript
复制


+ (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 evaluateWithObject:name];
    return isMatch;
      
}

js的写法:

代码语言:javascript
复制
  pattern: /^[0-9a-zA-Z\u4E00-\u9FA5][0-9a-zA-Z\u4E00-\u9FA5-\\]{0,}$/,

2.2 基本校验例子

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

代码语言:javascript
复制

+ (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 evaluateWithObject:password];
    return isMatch;
      
}


正则匹配手机号

代码语言:javascript
复制

+ (BOOL)checkTelNumber:(NSString *) telNumber
{
    NSString *pattern = @"^1+[3578]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:telNumber];
    return isMatch;
}
  
  
 #pragma 正则匹员工号,12位的数字
+ (BOOL)checkEmployeeNumber : (NSString *) number
{
    NSString *pattern = @"^[0-9]{12}";
      
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:number];
    return isMatch;
      
}

正则匹配用户姓名,20位的中文或英文

代码语言:javascript
复制


+ (BOOL)checkUserName : (NSString *) userName
{
    NSString *pattern = @"^[a-zA-Z\u4E00-\u9FA5]{1,20}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:userName];
    return isMatch;
      
}
  
  
#pragma 正则匹配用户身份证号15或18位
+ (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 evaluateWithObject:idCard];
    return isMatch;
}
  
  

正则匹配URL

代码语言:javascript
复制
+ (BOOL)checkURL : (NSString *) url
{
    NSString *pattern = @"^[0-9A-Za-z]{1,50}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:url];
    return isMatch;
      
}

2.3 限制UITextField只能输入金额

代码语言:javascript
复制
+ (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 evaluateWithObject:str] && [predicate1 evaluateWithObject:str] ? YES : NO;
    
}


/**
 限制UITextField只能输入金额的正则表达式
 @param textField <#textField description#>
 @param range <#range description#>
 @param string <#string description#>
 @return <#return value description#>
 */
- (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 [QCT_Common isAmoutshouldChangeCharactersInRange:str];
    
    
    
    
}

2.4 Url格式校验

代码语言:javascript
复制
+(BOOL)isUrl:(NSString *)url{
    NSString *regex =@"[a-zA-z]+://[^\\s]*";
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [urlTest evaluateWithObject:url];
}



  • 用法举例:自定义NSURLProtocol, 决定请求是否需要当前协议对象处理
代码语言:javascript
复制
/**
 决定请求是否需要当前协议对象处理

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

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

代码语言:javascript
复制
/**
 * 判断字符串是否为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 [predicate evaluateWithObject:text];
}


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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-07-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 iOS逆向 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 引言
  • I 前置知识
    • 1.1 Parser Basics
      • 1.2 Basic Comparisons
        • 1.3 Basic Compound Predicates
          • 1.4 String Comparisons
            • 1.5 Aggregate Operations
              • 1.6 Identifiers
                • 1.7 Literals
                  • 1.8 Reserved Words
                  • II NSPredicate在正则表达式的应用
                    • 2.1 商品分类名称
                      • 2.2 基本校验例子
                        • 2.3 限制UITextField只能输入金额
                          • 2.4 Url格式校验
                            • 2.5 判断字符串是否为IP地址
                              • 2.6 正则表达式的一些元字符
                              • III 从数组搜索特定条件的元素
                              相关产品与服务
                              腾讯电子签
                              弹指间,放心签。腾讯电子签(E-Sign Service)致力为企业及个人提供极简且高效的电子合同管理工具。您只需要一部手机即可完成合同签约及常见的合同管理操作;电子签将对签约全程进行区块链记录,为您的业务与生活保驾护航。
                              领券
                              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档