前言
小知识,大挑战!本文正在参与“程序员必备小知识”创作活动
正则表达式一直是我的弱点,对这块儿知识真的是一窍不通,准备好好学习一下,总结正则表达式基础:修饰符、方括号
修饰符
i 执行对大小写不明感的匹配
语法: new RegExp('regexp', 'i') 或 /regexp/i
var str = '学不完的Font-End.卷它'
// console.log(str.match(/fONT-eND/i))
// [ 'Font-End', index: 4, input: '学不完的Font-End.卷它', groups: undefined ]
复制代码
g 执行全局匹配 (查找所有匹配而非找到第一个匹配后停止)
语法:new RegExp('regexp', 'g') 或 /regexp/g
var str = '学不完的Font-End.Font-End卷'
console.log(str.match(/Font-End/g))
// [ 'Font-End', 'Font-End' ]
复制代码
m 执行多行匹配
语法:new RegExp('regexp', 'm') 或 /regexp/m
var str = '学不完的\n Font-End.卷它'
console.log(str.match(/Font/m))
// [ 'Font', index: 6, input: '学不完的\n Font-End.卷它', groups: undefined ]
复制代码
组合使用
var str = 'Study Font-End'
console.log(str.match(/[stu]/gi))
// [ 'S', 't', 'u', 't' ]
复制代码
方括号 (字符类)
[xxx] 查找方括号之间的任何字符
var str = 'Study Font-End'
console.log(str.match(/[stu]/g))
// [ 't', 'u', 't' ]
复制代码
[^xxx] 查找任何不在方括号之间的任何字符
var str = 'Font-End'
console.log(str.match(/[^FE]/g))
// [ 'o', 'n', 't', '-', 'n', 'd' ]
复制代码
[0-9] 查找任何0-9的数字
var str = '17602345678'
console.log(str.match(/[5-8]/g))
// [ '7', '6', '5', '6', '7', '8' ]
复制代码
[a-z] 查找任何a-z的数字
var str = 'Font-End'
console.log(str.match(/[n-t]/g))
// [ 'o', 'n', 't', 'n' ]
复制代码
[A-Z] 查找任何A-Z的数字
var str = 'Font-End'
console.log(str.match(/[E-G]/g))
// [ 'F', 'E' ]
复制代码
[shuffle] 查找任何A-Z的数字
var str = 'Font-End'
console.log(str.match(/[Fnd]/g))
// [ 'F', 'n', 'n', 'd' ]
复制代码
[abc|DEF|xYz] 查找任何A-Z的数字
var str = 'Font-End'
console.log(str.match(/[F|n]/g))
// [ 'F', 'n', 'n' ]
复制代码
结语
后续继续发布量词,元字符、断言、练习题