//练习1 ,拼配abc
// 创建字符串
let str1 = "asdfasgeabcdeeabc"
//1.创建拼配规则
let pattern = "abc"
//2. 创建这正则表达式对象
let regex = try? NSRegularExpression(pattern: pattern, options: []);
//3. 匹配字符串中的内容
guard let results = regex?.matches(in: str1, options: [], range: NSRange(location: 0, length: str1.count)) else
{
return
}
//4. 遍历结果
for result in results
{
print((str1 as NSString).substring(with: result.range) )
print(result)
}
//练习2:包含一个a~z,后面必须是0~9 -->[a-z][0-9]或者[a-z]\d
let str2 = "034a5v6e436"
//1创建拼配规则
let pattern2 = "[a-z][0-9]"
//2. 创建正则拼配对象
let regex2 = try? NSRegularExpression(pattern: pattern2, options: [])
//3.匹配字符串
guard let results2 = regex2?.matches(in: str2, options: [], range: NSRange(location: 0, length: str2.count)) else
{
return
}
//4. 遍历匹配结果
for result2 in results2 {
print((str2 as NSString).substring(with: result2.range))
}
//练习3. 练习3:必须第一个是字母,第二个是数字 -->^[a-z][0-9]$
// ^[a-z] : 表示首字母必须是a~z
//* \d{2,10} : 数字有2到10
//* [a-z]$ : 表示必须以a-z的字母结尾
let str3 = "a3fjasterndalgi"
//1. 创建拼配规则
let pattern3 = "^[a-z][0-9]"
//2. 创建正则拼配对象
let regex3 = try? NSRegularExpression(pattern: pattern3, options: [])
//3. 匹配字符串
guard let results3 = regex3?.matches(in: str3, options: [], range:
NSRange(location: 0, length: str3.count)) else
{
print("没有匹配结果")
return;
}
//遍历匹配结果
for result3 in results3
{
print((str3 as NSString).substring(with: result3.range))
}
//练习4: 必须第一个是字母,字母后面跟上4~9个数字
let str4 = "a23456fads46534fa"
//1. 创建匹配规则
let pattern4 = "^[a-z][0-9]{4,9}"
//2. c创建正则匹配对象
let regex4 = try? NSRegularExpression(pattern: pattern4, options: [])
//3. 匹配字符串
guard let results4 = regex4?.matches(in: str4, options: [], range: NSRange(location: 0, length: str4.count)) else
{
return
}
for result4 in results4
{
print((str4 as NSString).substring(with: result4.range) )
}
//练习5:不能是数字0-9
let str5 = "dsf3iah3g4i3"
//5.1 创建匹配规则
let pattern5 = "[^0-9]"
//5.2 创建正则匹配对象
let regex5 = try? NSRegularExpression(pattern: pattern5, options: [])
//5.3 匹配字符串
guard let results5 = regex5?.matches(in: str5, options: [], range: NSRange(location: 0, length: str5.count)) else {
return
}
//5.4 遍历结果
for result5 in results5
{
print((str5 as NSString).substring(with: result5.range))
}
//练习6: qq匹配
/*
都是数字
5~12位
并且第一位不能是0
*/
let str6 = "759542164"
//1. 创建匹配规则
let pattern6 = "^[1-9][0-9]{4,12}$"
//2. 创建正则匹配对象
let regex6 = try? NSRegularExpression(pattern: pattern6, options: [])
//3. 匹配字符串
guard let results6 = regex6?.matches(in: str6, options: [], range: NSRange(location: 0, length: str6.count)) else
{
print("不是QQ号");
return
}
if results6.count > 0 {
print("是qq号")
}
/*练习7:手机号码匹配^1[3578]\d{9}$
1.以13/15/17/18
2.长度是11
*/
let str7 = "181a20612556a"
//1.创建匹配规则
let pattern7 = "^1[3578][0-9]{9}$"
//2.创建正则匹配对象
let regex7 = try? NSRegularExpression(pattern: pattern7, options: [])
//3. 匹配字符串
guard let results7 = regex7?.matches(in: str7, options: [], range: NSRange(location: 0, length: str7.count)) else
{
return
}
if results7.count > 0 {
print("是手机号")
}else
{
print("不是手机号")
}
网友评论