RegExp 基础(一)

前言

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动

正则表达式一直是我的弱点,对这块儿知识真的是一窍不通,准备好好学习一下,总结正则表达式基础:修饰符、方括号

修饰符

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' ]

结语

后续继续发布量词,元字符断言练习题

参考

菜鸟教程