正则表达式
1. 什么是正则表达式?
-
正则表达式是由一个字符序列形成的搜索模式。
-
当你在文本中搜索数据时,你可以用搜索模式来描述你要查询的内容。
-
正则表达式可以是一个简单的字符,或一个更复杂的模式。
-
正则表达式可用于所有文本搜索和文本替换的操作。
2. 正则表达式的创建
2.1 字面量
// 在一对反斜线中写正则表达式内容,如/abc/
// 正则表达式里面不需要加引号 不管是数字型还是字符串型
var reg = /正则表达式/修饰符;
var reg = /hello/g;
2.2 构造函数
//构造正则表达式的实例,如new RexExp('abc')
//内部传入的参数为字符串/字符串的变量
var reg =new RegExp("正则表达式","修饰符")
var reg =new RegExp("hello","g");
3. 字符分类
3.1 普通字符
字母、数字、下划线、汉字、没有特殊含义的符号(,;!@等)
3.2 特殊字符
\:将特殊字符转义成普通字符
3.3 模式修饰符
- i:ignoreCase,匹配时忽视大小写
- m:multiline,多行匹配
- g:global,全局匹配
字面量创建正则时,模式修饰符写在一对反斜线后
4. 正则表达式实例方法
4.1 exec
匹配到返回值是一个result数组:[匹配的内容,index: 在str中匹配的起始位置,input: 参数字符串,groups: undefined] 否则返回null
var str = 'hello123 world hello javascript';
// 字面量
// 如果没有设置一个全局模式 每次都会回到索引0的位置重新查找
var reg = /hello/g;
// exec匹配成功返回一个数组 失败则会返回null
console.log(reg.lastIndex); //0
console.log(reg.exec(str)); //[ 'hello',index: 0,input: 'hello123 world hello javascript',groups: undefined ]
console.log(reg.exec(str)); //[ 'hello',index: 15,input: 'hello123 world hello javascript',groups: undefined ]
console.log(reg.lastIndex); //20
// 利用循环查看每次exec校验之后的结果
while (true){
var result = reg.exec(str);
// 何时终止这个循环
if(!result){
break;
}
console.log(result[0],result['index']); //hello 0 hello 15
}
注意点:
- 如果正则表达式中有修饰符"g",这时,在正则表达式的实例reg中会维护lastIndex属性,记录下一次开始的位置,当第二次执行exec的时候,从lastIndex开始检索。
- 如果正则表达式中没有修饰符"g",不会维护lastIndex属性,每次执行从开始位置检索
4.2 test
用来测试待检测的字符串中是否有可以匹配到正则表达式的字符串,如果有返回true,否则返回false
// test匹配成功 返回true 失败返回false
var str = 'hello123 world hello javascript';
var reg = /hello/g;
console.log(reg.test(str)); //true
注意点:
- 如果正则表达式中有修饰符"g",这时,在reg中会维护lastIndex属性,记录下一次开始的位置,当第二次执行test的时候,从lastIndex开始检索。
- 如果正则表达式中没有修饰符"g",不会维护lastIndex属性,每次执行从开始位置检索
4.3 toString/toLocaleString
// toString toLocaleString 返回 /hello/ 字符串
var str = 'hello123 world hello javascript';
var reg = /hello/g;
console.log(reg.toString(str)); // /hello/g
console.log(reg.toLocaleString(str)); // /hello/g
4.4 valueOf
// 返回正则表达式本身
var str = 'hello123 world hello javascript';
var reg = /hello/g;
console.log(reg.valueOf()); // /hello/g
5 正则表达式实例属性
5.1 lastIndex
当没设置全局匹配时,该属性值始终为0。每次正则查找的起点就是lastIndex。
// lastIndex 如果没有开启全局匹配模式 始终为0 每次校验都会从开始位置重新校验
// 如果开启了全局模式 每次校验都会记录当前满足条件的字符的位置 下次校验从这个位置开始
var str = 'hello hello hello';
var reg1 = /hello/;
var reg2 = /hello/g;
// 没有开启全局模式的
console.log(reg1.lastIndex); //0
console.log(reg1.exec(str)); //[ 'hello',index: 0,input: 'hello hello hello',groups: undefined ]
console.log(reg1.lastIndex); //0
// 开启全局模式的
var str = 'hello hello hello';
var reg1 = /hello/;
var reg2 = /