规则
/ $/ 结束
^ 以 开头
\d 数字
?可以不存在
js用法
// test, 返回Boolean
/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/.test('#FFF') // true
// replace
'11#FFF11#FFFFFF'.replace(/#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})/g,'替换后') // '11替换后11替换后'
// match, 返回Array
`"The rain in SPAIN stays mainly in the plain"`.match(/ain/gi) // ’ain,AIN,ain,ain‘
常用
16进制颜色
/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/
url
/^((https?):)?\/\/([^?:/]+)(:(\d+))?(\/[^?]*)?(\?(.*))?/
邮箱
^[A-Za-z0-9-_\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$
手机号
/^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
身份证
/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|10|11|12)(0[1-9]|[1-2]\d|30|31)\d{3}[\dX]$/
密码
/^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*?])\S*$/
提取HTML
const str = `<div class="header-box" name="header">`
const mt = str.match(/<\w+\s*([^>]*)\s*>/)
// properties 即 属性字符串,即 class="header-box" name="header"
const properties = mt[1]
const mt1 = properties.match(/([^\s=]+)(=(["'])(.*?)\3)?/g)
const obj = {}
if (mt1) {
mt1.forEach(p => {
const kv = p.trim().split('=')
obj[kv[0].trim()] = kv[1].trim().slice(1, -1)
})
}
// obj => { class: 'header-box', name: 'header' }