初始化的方式:
1.检索值是否存在一个范围区间里
var number2 = 0
var numberPre2 = NSPredicate(format: "SELF BETWEEN{1,5}")
var bool2 = numberPre2.evaluateWithObject(number2)
打印结果
当number2 = 0 打印:bool2 为false
当number2 = 1 打印:bool2 为true
2.检索数组元素中是否包含给定字符串
var number2 = "dd"
var numberPre2 = NSPredicate(format: "SELF IN {'dd','bb'}")
var bool2 = numberPre2.evaluateWithObject(number2)
其中出现的关键字
(BETWEEN、IN)称为范围运算符
SELF表示的是字符串本身,在本例代码中相当于变量number2
当然以数组的形式初始化NSPredicate也是可以的
var sets = ["dd","ss"]
var numberPre2 = NSPredicate(format: "SELF IN %@",sets)
3.字符串操作相关
1>判断字符串中是否包含另一个字符串CONTAINS
var str3 = "dd"
var pre3 = NSPredicate(format: "SELF CONTAINS[cd] %@", str3)
var bool3 = pre3.evaluateWithObject("dsadd")
打印结果
当str3="da" 打印:bool3=false
当str3="dd" 打印:bool3=true
2>判断是否以某个字符串开头BEGINSWITH
var str3 = "dd"
var pre3 = NSPredicate(format: "SELF BEGINSWITH[cd] %@", str3)
var bool3 = pre3.evaluateWithObject("ddacd")
打印结果
当str3="da" 打印:bool3=false
当str3="dd" 打印:bool3=true
3>判断是否以某个字符串结尾ENDSWITH
var str3 = "dd"
var pre3 = NSPredicate(format: "SELF ENDSWITH[cd] %@", str3)
var bool3 = pre3.evaluateWithObject("dcadd")
打印结果
当str3="da" 打印:bool3=false
当str3="dd" 打印:bool3=true
注:
[c]不区分大小写
[d]不区分发音符号即没有重印符号
[cd]表示即不区分大小写,也不区分发音符号
4.模糊查询LINK通配符
5.正则表达式MATCHES
//匹配纯数字
var number = "^[0-9]+$"
var numberPre = NSPredicate(format: "SELF MATCHES %@", number)
var boo3 = numberPre.evaluateWithObject("13140000000")
打印结果为 true
6.基本操作符运算
let predicate = NSPredicate(format: "(SELF > 20) AND (SELF < 30)")
let boo7 = predicate.evaluateWithObject(num)
print(boo7)
打印结果
当num = 20 打印:false
当num = 21 打印:true
实际应用
1.检索一个数组中所有包含此字符串的元素,并返回一个结果的数组
let arr4 = ["beijing" , "shanghai" , "guangzhou" , "wuhan"] asNSMutableArray
let str4 = "ang"
let pre4 = NSPredicate(format: "SELF CONtAINS %@", str4)
arr4.filterUsingPredicate(pre4)
打印arr4 结果为
["shanghai","guangzhou"]
2.判断字符串首字符是否为字母
let regex1 = "[A-Za-z]+"
let pre5 = NSPredicate(format: "SELF MATCHES %@" , regex1)
let bool5 = pre5.evaluateWithObject("2")
转载: https://www.jianshu.com/p/bfdacbdf37a7
// 实际应用的情况 如下
================================================
import UIKit
let validDomainsIncludesSubDomain: [String] = [
"xjpCjp.co.jp"
]
let pathArray: [String] = [
"/a/b/c"
]
let validationPredicate: NSPredicate = {
let host: NSPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: validDomainsIncludesSubDomain.map({ NSPredicate(format: "host ENDSWITH %@", $0) }))
let path: NSPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: pathArray.map({ NSPredicate(format: "path BEGINSWITH %@", $0) }))
return NSCompoundPredicate(andPredicateWithSubpredicates: [host, path])
}()
let url = URL(string: "https://xjpCjp.co.jpp/a/b/c")!
print("My Host: ",url.host ?? "")
print("My Path: ", url.path)
print("absoluteString: ", url.absoluteURL)
let validOpenInAppBrowser = validationPredicate.evaluate(with: url)
print("validOpenInAppBrowser IS:", validOpenInAppBrowser)