返回所有匹配结果
func matches(pattern: String, validate: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matches(in: validate, options: [], range: NSMakeRange(0, validate.count))
var datas: [String] = []
matches.forEach { result in
let startIdx = validate.index(validate.startIndex, offsetBy:result.range.location)
let endIdx = validate.index(validate.startIndex, offsetBy: result.range.length - 1)
let newStr = validate[startIdx...endIdx]
datas.append("\(newStr)")
// let newStr = (validate as NSString).substring(with: result.range)
// datas.append(newStr)
}
return datas
}
catch {
return []
}
}
测试用例:
let pattern = "^(10001|10002)$"
let validate = "10001"
let newStr = matches(pattern: pattern, validate: validate)
print("匹配结果:\(newStr)")
打印结果:
匹配结果:["10001"]
获取第1个匹配的结果
func firstMatch(pattern: String, validate: String) -> String {
do {
let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let result = regex.firstMatch(in: validate, range: NSMakeRange(0, validate.count))
guard let result else { return "" }
let startIdx = validate.index(validate.startIndex, offsetBy:result.range.location)
let endIdx = validate.index(validate.startIndex, offsetBy: result.range.length - 1)
let newStr = validate[startIdx...endIdx]
return "\(newStr)"
} catch {
return ""
}
}
测试用例:
let pattern = "runoob(?=[\\d+])"
let validate = "runoob12runoobdrunooB3"
let newStr = firstMatch(pattern: pattern, validate: validate)
print("匹配结果:\(newStr)")
打印结果:
匹配结果:runoob
获取匹配的数量
func numberOfMatches(pattern: String, validate: String) -> Int {
do {
// options: [] 区分大小写,严格匹配
// options: .caseInsensitive 不区分大小写
let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let number = regex.numberOfMatches(in: validate, range: NSMakeRange(0, validate.count))
return number
} catch {
return 0
}
}
测试用例:
let pattern = "runoob(?=[\\d+])"
let validate = "runoob12runoobdrunooB3"
let matchCount = numberOfMatches(pattern: pattern, validate: validate)
print("匹配数量:\(matchCount)")
打印结果:
// options: .caseInsensitive 不区分大小写
匹配数量:2
// options: [] 区分大小写,严格匹配
匹配数量:1
字符串正则替换
func matchReplace(pattern: String, validate: String, replacing: String) -> String {
do {
let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let modified = regex.stringByReplacingMatches(in: validate, options: .reportProgress, range: NSMakeRange(0, validate.count), withTemplate: replacing)
return modified
} catch {
return validate
}
}
测试用例:
let replacePattern = "[0-9]+"
let validateStr = "12-ab-3-c"
let replacingStr = "ufo"
let modified = matchReplace(pattern: replacePattern, validate: validateStr, replacing: replacingStr)
print("替换后:\(modified)")
打印结果:
替换后:ufo-ab-ufo-c