正则表达式
正则表达式(Regular Expression,在代码中常简写为regex、regexp或RE)使用单个字符串来描述、匹配一系列符合某个句法规则的字符串搜索模式。
1 什么是正则表达式?
正则表达式是由一个字符序列形成的搜索模式。
当你在文本中搜索数据时,你可以用搜索模式来描述你要查询的内容。
正则表达式可以是一个简单的字符,或一个更复杂的模式。
正则表达式可用于所有文本搜索和文本替换的操作。
2 两种创建方式
// 在一对反斜线中写正则表达式内容,如/abc/
// 正则表达式里面不需要加引号 不管是数字型还是字符串型
var reg = /正则表达式/修饰符;
var reg = /hello/g;
//构造正则表达式的实例,如new RexExp('abc')
//内部传入的参数为字符串/字符串的变量
var reg =new RegExp("正则表达式","修饰符")
var reg =new RegExp("hello","g");
3 字符分类
普通字符
字母、数字、下划线、汉字、没有特殊含义的符号(,;!@等)
实际上不是特殊字符的字符都是普通字符
特殊字符
\:将特殊字符转义成普通字符
模式修饰符
i:ignoreCase,匹配时忽视大小写
m:multiline,多行匹配
g:global,全局匹配
字面量创建正则时,模式修饰符写在一对反斜线后
4 实例方法
exec( )
可用来匹配字符串中符合正则表达式的字符串
概述
如果匹配到,返回值是一个result数组:
[匹配的内容,index: 在str中匹配的起始位置,input: 参数字符串,groups: undefined]
否则返回null
var str = 'hello world hello';
var reg1 = /hello/;
var reg2 = /hello/g;
var reg3 = /exe/g;
console.log(reg1.exec(str)); //[ 'hello', index: 0, input: 'hello world hello', groups: undefined ]
console.log(reg2.exec(str)); //[ 'hello', index: 0, input: 'hello world hello', groups: undefined ]
console.log(reg3.exec(str)); // null
// 如果是全局模式的正则验证 还可以使用循环进行输出
while(true)
var result = reg.exec(str);
if(!result){
break;
}
console.log(result[0],result["index"],reg.lastIndex);
}
注意点
1)如果正则表达式中有修饰符"g",这时,在正则表达式的实例reg中会维护lastIndex属性,记录下一次开始的位置,当第二次执行exec的时候,从lastIndex开始检索。
2)如果正则表达式中没有修饰符"g",不会维护lastIndex属性,每次执行从开始位置检索
test( )
用来测试待检测的字符串中是否有可以匹配到正则表达式的字符串,如果有返回true,否则返回false
var str = 'hello world';
var reg1 = /world/;
var reg2 = /Regex/;
console.log(reg1.test(str)); //返回true
console.log(reg2.test(str)); //返回false
注意点
1)如果正则表达式中有修饰符"g",这时,在reg中会维护lastIndex属性,记录下一次开始的位置,当第二次执行test的时候,从lastIndex开始检索。
2)如果正则表达式中没有修饰符"g",不会维护lastIndex属性,每次执行从开始位置检索
toString/toLocaleString( )
把正则表达式的内容转化成字面量形式字符串/有本地特色的字符串(JS中没效果)
var reg1 = /hello/;
console.log(reg1.toString()); //返回 /hello/ 字符串
console.log(reg1.toLocaleString()); //返回 /hello/ 字符串
valueOf( )
返回正则表达式本身
var reg1 = /hello/;
console.log(reg1.valueOf()); // 返回正则表达式本身
5 实例属性
lastIndex
当没设置全局匹配时,该属性值始终为0
设置了全局匹配时,每执行一次exec/test来匹配,lastIndex就会移向匹配到的字符串的下一个位置,当指向的位置后没有可以再次匹配的字符串时,下一次执行exec返回null,test执行返回false,然后lastIndex归零,从字符串的开头重新匹配一轮
可以理解成,每次正则查找的起点就是lastIndex
var str = 'hello hello hello';
var reg1 = /hello/;
var reg2 = /hello/g;
console.log(reg1.lastIndex); // 0
console.log(reg1.exec(str)); // 返回第一个hello
console.log(reg1.lastIndex); // 0
console.log(reg2.lastIndex); // 0
console.log(reg2.exec(str)); // 返回第一个hello
console.log(reg2.lastIndex); // 5
console.log(reg2.lastIndex); // 5
console.log(reg2.exec(str)); // 返回第二个hello
console.log(reg2.lastIndex); // 11
console.log(reg2.lastIndex); // 11
console.log(reg2.exec(str)); // 返回第三个hello
console.log(reg2.lastIndex); // 17
console.log(reg2.exec(str)); //返回 null
console.log(reg2.lastIndex); // 0
console.log(reg2.exec(str)); // 返回第一个hello