5.4 RegExp类型
ECMAScript通过RegExp类型来支持正则表达式。
var expression = / pattern / flags ;
字面量模式中使用的所有元字符都必须转义。正则表达式中的元字符包括:( [ { \ $ | ) ? * + . ] }
构造函数中要用双重转义,才能使用。
// 匹配第一个"bat"或"cat",不区分大小写
// 字面量形式:
var pattern1 = / [bc]at /i;
// 构造函数创建的:
var pattern2 = new RegExp("[bc]at", "i");
在ECMAScript 3中,正则表达式字面量始终会共享同一个RegExp实例,而使用构造函数创建的每一个新RegExp实例都是一个新实例。
但是!!!!!!
ECMAScript 5明确规定,使用正则表达式字面量必须像直接调用RegExp构造函数一样,每次都创造新的RegExp实例。(这就是为什么后续跟着调试,字面量不会出现flase的原因 0 0. 时间:2020/4/1 js高程3 P105)。
5.4.1 RegExp 实例属性
5.4.2 RegExp实例方法
RexExp对象的主要方法是exec(), exex()接受一个要应用模式的字符串,然后返回包含第一个匹配项信息的数组;或者在没有匹配的情况下返回null。
返回的数组虽然是Array实例,但包含的两个额外的属性:index和input。
例子:
var text = "abb acc mom and dad and baby", pattern = /mom( and dad( and baby)?)?/gi; matches = pattern.exec(text); console.log(matches.index); //8 (index表示匹配项在字符串的位置) console.log(matches.input); //"abb acc mom and dad and baby" (input表示应用正则表达式的字符串) console.log(matches[0]); //"mom and dad and baby" (数组中第一项是与整个模式匹配的字符串) console.log(matches[1]); //" and dad and baby" (其他项是与模式中的捕获组匹配的字符串) console.log(matches[2]); //" and baby" (同上)
对于exec()方法而言,在不设置全局标志的情况下,在同一个字符串上多次调用exec()将始终返回第一个匹配项信息。而在设置全局标志的情况下,每次调用exec()则都会在字符串中继续查找新匹配项。lastIndex属性用于规定下次匹配的起始位置。
例子:
var text = "cat, bat, sat, fat", pattern1 = /.at/; var matches = pattern1.exec(text); console.log(matches.index); //0 console.log(matches.input); //cat, bat, sat, fat console.log(matches[0]); //cat console.log(pattern1.lastIndex); //0 matches = pattern1.exec(text); console.log(matches.index); //0 console.log(matches.input); //cat, bat, sat, fat console.log(matches[0]); //cat console.log(pattern1.lastIndex); //0 var pattern2 = /.at/g; var matches = pattern2.exec(text); console.log(matches.index); //0 console.log(matches.input); //cat, bat, sat, fat console.log(matches[0]); //cat console.log(pattern2.lastIndex); //3 matches = pattern2.exec(text); console.log(matches.index); //5 console.log(matches.input); //cat, bat, sat, fat console.log(matches[0]); //bat console.log(pattern2.lastIndex); //8
正则表达式的第二个方法是test(),接受一个字符串参数。在模式与该参数匹配的情况下返回ture;否则,返回false。
在只想知道目标字符串与某个模式是否匹配,但不需要知道内容,这个方法很方便。经常被用在 if 语句中。
例如:
var text = "000-00-0000"; var pattern = /\d{3}-\d{2}-\d{4}/; if (pattern.test(text)){ alert("hhhhh"); }
原文:https://www.cnblogs.com/CZheng7/p/12612545.html