import Foundation
let pattern = ##"""
^ # 匹配行首
(?=.*[A-Z]) # 向前环视,匹配到大写字母
(?=.*[a-z]) # 向前环视,匹配到小写字母
(?=.*\d) # 向前环视,匹配到数字
(?=.*[_\W]) # 向前环视,匹配到特殊字符
.{10,} # 若满足以上环视条件,且有10个以上字符,则进行匹配
$ # 匹配行尾
"""##
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .allowCommentsAndWhitespace])
let testString = #"""
// Good Case
asdfsadfANVasdfasdfasdf..sadfs1
www.baidu.com.COM123
qwerTYUIOP1233333333333333
qwerTYUIOP1233333333333333-=+
asdfsafxxxSSS..123
abcABC123,./
// Bad Case
xxxyyyzzz
XYZxyz123
aaabbbccc
12342353125123asedf
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression