创建方法
1.字面量
let reg = /\bis\b/g; //g表示全文匹配
let str = "He is a boy. This is a dog. Where is she?";
console.log(str.replace(reg, "IS"));
2.构造函数
let reg = new RegExp("\\bis\\b", "g");
let str = "He is a boy. This is a dog. Where is she?";
console.log(str.replace(reg, "IS"));
基础
反向类
<script>
var str = "He is a boy.Is he?";
console.log(str.replace(/\bis\b/gi, "0")); //He 0 a boy.0 he?
</script>
<script>
// 全文搜索a,b,c替换为x
var str = "a1b2c3a4b5c6";
console.log(str.replace(/[abc]/g, "x")); //x1x2x3x4x5x6
</script>
<script>
// 全文搜索除了a,b,c的字符,替换为x
var str = "a1b2c3a4b5c6";
console.log(str.replace(/[^abc]/g, "x")); //axbxcxaxbxcx
</script>
范围类
<script>
var str = "a1b2c3a4b5c6";
console.log(str.replace(/[a-z]/g, "X")); //X1X2X3X4X5X6
</script>
<script>
var str = "a1b2c3a4b5c6";
console.log(str.replace(/[a-zA-Z0-9]/g, "*")); //************
</script>
<script>
var str = "2020-03-21";
// 数字和短横线(0-9中的-表示0到9,后面的-表示短横线)顺序不能改变
console.log(str.replace(/[0-9-]/g, "0")); //0000000000
</script>
贪婪和非贪婪模式
<script>
// 贪婪模式(尽可能多的匹配)
console.log("12345678".replace(/\d{3,6}/g, "x")); //x78
// 非贪婪模式(尽可能少的匹配)
console.log("12345678".replace(/\d{3,6}?/g, "x")); //xx78
</script>
分组
<script>
// 分组
console.log("a1b2c3d4".replace(/[a-z]\d{3}/g,"x"));//a1b2c3d4
console.log("a1b2c3d4".replace(/([a-z]\d){3}/g,"x"));//xd4 表示3组字母加数字,即a1b2c3被x替代
</script>
或
<script>
// 或
console.log("ByronCasper".replace(/Byron|Casper/g,"x"));//xx
console.log("ByrCasperByronsper".replace(/Byr(on|Ca)sper/g,"x"));//xx
</script>
反向引用
<script>
// 反向引用
console.log("2020-03-04".replace(/(\d{4})-(\d{2})-(\d{2})/g,"$2/$3/$1"));//03/04/2020
// 忽略分组采用 ?:
console.log("2020-03-04".replace(/(\d{4})-(\d{2})-(?:\d{2})/g,"$2/$3/$1"));//03/$3/2020
console.log("2020-03-04".replace(/(\d{4})-(?:\d{2})-(\d{2})/g,"$2/$3/$1"));//04/$3/2020
</script>
前瞻
<script>
// 前瞻 assert是断言,不参与匹配
// 正向前瞻exp(?=assert)
// 负向前瞻exp(?!assert)
console.log("a2*34V8".replace(/\w(?=\d)/g,"x"));//x2*x4x8
console.log("a2*34V8".replace(/\w(?!\d)/g,"x"));//ax*3xVx
</script>
总结
- i 忽略大小写,正则表达式对大小写敏感
- m 多行搜索,搜索时识别换行符
- t 制表符
- g 表示全文匹配
- \b 匹配单词边界
- . 除了回车符和换行符之外的所有字符
- \d 数字字符[0-9]
- \D 非数字字符[^0-9]
- \s 空白符
- \S 非空白符
- \w 单词字符[a-zA-Z0-9]
- \W 非单词字符
- ^ 匹配输入字首行 在[]之外表示边界符,[]内表示取反
- $ 匹配输入字尾行
- \b 单词边界
- \B 非单词边界
- \f 匹配一个换页符
- \r 匹配一个回车符
- \n 匹配一个换行符
- \v 匹配一个垂直制表符
- < > 匹配词的开始(<)和结束(>)
- () 将()之间的表达式定义为组
// 量词
// + 匹配前面一个表达式 1 次或者多次。
// ? 匹配前面的子表达式零次或一次。
// * 匹配前面的子表达式任意次。例如,zo*能匹配"z",也能匹配"zo"以及"zoo"
// {n} 出现n次
// {n,m}出现n到m次
// {n,}出现n次或多次
// | 或,左右字符二选一