步骤
- 创建规则
let pattern = "^[a-z]\\d"
- 创建正则表达式对象
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
return
}
- 匹配字符串中的内容
let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.count))
for result in results {
print((str as NSString).substring(with: result.range))
}
简单常用规则
- [a-z] :匹配字符a~z
- [0-9] :匹配数字0~9 (另外种写法\d)
- ^[a-z]:表示首字符必须是字母a~z
- \d{2,10}:数字2到10个
- [a-z]$:表示必须以字母a~z结尾
- [^0-9]:表示不能是0~9