正则表达式
是一种模式 用于匹配字符串的模式
javascript中内置的对象—RegExp
代码中简写regex、regexp、RE
-
创建正则对象
构造函数方式
let reg = new RegExp(‘\d+’)
字面量方式
let reg = /\d+/ -
正则常用方法
- test匹配
正则对象.test(字符串) 返回true | false
const str = 'abcdef' // 字符串
const reg = /c/ // 正则
let isOk = reg.test(str)
- search查找,返回下标 ,不成功返回-1
字符串.search(正则)
const str = 'abcdef'
const reg = /c/
let index = str.search(reg)
- match 正则去匹配字符串,返回成功的数组,失败返回null
字符串.match(正则)
const str = 'Dgfhfgh254bhku289fgdhdy675gfh'
const reg = /\d+/g
let arr = str.match(reg)
- replace替换 替换成新字符串
字符串.replace(正则,新字符)
const str = 'abcdef'
const reg = /b/
let newStr = str.replace(reg, '*')
console.log(newStr)
- exec 正则去匹配字符串,返回成功的数组,失败返回null
正则.exec(字符串)
返回的数组里:index:第一个匹配字符串的下标;input:原字符串;groups:命名分组时匹配到的分组对象!
[0-9] 表示0~9 数字
转义字符:
n -> \n
. -> .
练习–邮箱、密码、电话号、
<script>
/**
* 1.已知邮箱字符串'zhousir028@163.com'写正则匹配该邮箱字符串是否符合邮箱格式?
邮箱格式要求:
1. 必须包含@符号
2. @符号左右两边可以字母或数字或字母数字组合
3. 以.com结尾
*
*/
function test1() {
const email = 'zhousir028@qq.com'
const reg = /[0-9a-zA-Z]+@[0-9a-zA-Z]+\.com$/
//+ 代表至少出现一个
if(reg.test(email)){
alert('正确邮箱格式')
}else{
alert('错误的邮箱格式')
}
}
// test1()
2. 已知密码字符串'Zhousir12345' 写正则匹配密码是否符合密码强度规则?
密码强度规则:
1. 必须是大写字母开头
2. 密码包含字母和数字
3. 至少8位
*/
function test2() {
const password = 'ZHousir12'
const reg = /[A-Z][0-9a-zA-Z]{7,}/
//至少一位大写,后边就是至少七位,后边的也包括大写[0-9a-zA-Z]{7,}
if(reg.test(password)){
alert('正确密码格式')
}else{
alert('错误的密码格式')
}
}
// test2()
/*
3. 已知手机字符串'18012345678' 匹配中国手机号是否正则
中国手机号规则: 1. 以1开头 ^1
2.第二位是 3或5或8
3. 总共11位
*/
function test3() {
const phone = '13012345678'
const reg = /^1[3|5|8]\d{9}$/
//\d{9}任意数字--九位
if(reg.test(phone)){
alert('正确手机格式')
}else{
alert('错误的手机格式')
}
}
// test3()
/*
4. 用正则表达式匹配的是中国的电话号码,以0开头,然后是两个数字,然后是一个连字号“-”,最后是8个数字
*/
function test4() {
const phone2 = '028-12345678'
const reg = /^0\d{2}-\d{8}$/ // 匹配座机电话模式 // 量词-限定符
let isOk = reg.test(phone2)
alert(isOk)
}
/*
5. 将字符串中单词is替换成 'are'字符串如下:
'He is a boy, This is a dog.Where is she?'
*/
function test5() {
const str = 'He is a boy, This is a dog.Where is she?'
const reg = /\bis\b/g
//加\b 确保是is单词
let newStr = str.replace(reg,'are')
console.log(newStr);
}
test5()
贪婪模式和非贪婪模式
非贪婪模式
分组–加括号
(abc)? 表示0个或1个abc abc表示一个分组
const str = ‘abcdefabc’
const reg = /(abc)+/g
反向引用
const str = '2022-09-05' //-> 09/05/2022
const reg = /(\d{4})-(\d{2})-(\d{2})/
// $1 $2 $3
let newStr = str.replace(reg,'$2/$3/$1')
console.log(newStr)