RegExp 对象
简介:
- 用于规定在文本中检索的内容。
- 表示正则表达式,它是 对字符串执行模式匹配 的强大工具。
详解:
RegExp 是正则表达式的缩写。当您检索某个文本时,可以使用一种模式来描述要检索的内容。RegExp 就是这种模式。简单的模式可以是一个单独的字符。更复杂的模式包括了更多的字符,并可用于解析、格式检查、替换等等。您可以规定字符串中的检索位置,以及要检索的字符类型,等等。
RegExp 对象用于存储检索模式。
通过 new 关键词来定义 RegExp 对象。以下代码定义了名为 patt1 的 RegExp 对象,其模式是 “e”:
var patt1=new RegExp("e");
当您使用该 RegExp 对象在一个字符串中检索时,将寻找的是字符 “e”。
RegExp 对象的方法
RegExp 对象有 3 个方法:test()、exec() 以及 compile()。
- test() 方法检索字符串中的指定值。返回值是 true 或 false。
示例:
var patt1=new RegExp("e");
var a=patt1.test("Hello world!");//true
var b=patt1.test("today is sunday?")//false
解释:上面例子中a变量中存在e,所以返回true,b变量中不存在e,所以返回false;
- exec() 方法检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回 null。
示例:
var patt1=new RegExp("we");
var a=patt1.exec("what's the weather like today?");//["we", index: 11, input: "what's the weather like today?", groups: undefined]
var b=patt1.exec("today is sunday?")//null
示例:如果我们要匹配一个字符串中的所有字母呢,此时我们可以添加第二个参数g(“global”)表示全局查找。
在使用 “g” 参数时,exec() 的工作原理如下:(1)找到第一个 “e”,并存储其位置(2)如果再次运行 exec(),则从存储的位置开始检索,并找到下一个 “e”,并存储其位置。
var patt1=new RegExp("i","g");
var r;
do{
r=patt1.exec("this is or my haha");
console.log(r);
document.write(r);//iinull
}
while(r!=null)
//console.log(r);输出结果:
//["i", index: 2, input: "this is or my haha", groups: undefined]
//["i", index: 5, input: "this is or my haha", groups: undefined]
- compile() 方法用于改变 RegExp。既可以改变检索模式,也可以添加或删除第二个参数。
示例:
//检索e
var patt1=new RegExp("e");
console.log(patt1.test("the best in life are free"));//true
//把要检索的字母换成m
patt1.compile("m");
//由于这段字符里面不存在m,所以输出false
console.log(patt1.test("the best in life are free"));//false