/*
* RegExp:正则表达式的缩写
* RegExp对象的3个方法:test(),exec(),compile()
*/
var reg = new RegExp("e");
//创建一个正则对象的实例,在使用正则对象检索字符串时,查找字符“e”
//test()方法是检索字符串中指定的值,返回true或者false
var str = "thE World is the best";
console.log(reg.test(str));
if(reg.test(str)) console.log("匹配成功");
else console.log("匹配失败");
//exec()方法是检索字符串中指定的值,返回的是被查找的值,如果没有查找到,返回null
console.log(reg.exec(str));//返回数组
if(reg.exec(str) != null) console.log("匹配成功");
else console.log("匹配失败");
var reg01 = new RegExp("e","ig");//使用参数g,实现全局查找,参数二是查找模式,可以连写,可选
console.log(reg01.exec(str));
do{
var result = reg01.exec(str);
console.log(result);
}while (result != null)
/*
* exec()的工作原理:找到第一个匹配的字符,并且储存它的位置,如果在次运行,看从储存的
* 位置开始检索,并且找到下一个匹配的字符,再存储它的位置,以数组的形式返回
*/
//compile()用于该表RegExp,即可以改变检索模式,也可以去添加或者删除第二个参数
reg.compile("o");//改变检索模式
console.log(reg.exec(str));
reg01.compile("e");//去掉第二个参数
// do{
// var result = reg01.exec(str);
// console.log(result);
// }while (result != null) //死循环 每次都是从头开始找 每次都能找到e
正则对象
猜你喜欢
转载自blog.csdn.net/weixin_45936690/article/details/104552318
今日推荐
周排行