RegExp 对象的三个方法:compile()、exec()、test()

这三个都是RegExp对象下的三个方法,使用方法是一致得。javascript

使用方法:RegExpObject.方法()java

方法解析:其实就是根据定义好的正则对象,调用对应的方法。正则表达式

 

     1.RegExpObject.compile(RegExp,modifier)数组

     modifier 规定匹配的类型。"g" 用于全局匹配,"i" 用于区分大小写,"gi" 用于全局区分大小写的匹配。spa

     compile用于改变和从新编译正则表达式。   对象

var str="Every man in the world! Every woman on earth!";

patt=/man/g;
str2=str.replace(patt,"person");
document.write(str2+"<br />");

patt=/(wo)?man/g;
patt.compile(patt);
str2=str.replace(patt,"person");
document.write(str2); 

输出:blog

Every person in the world! Every woperson on earth!
Every person in the world! Every person on earth!

对patt正则进行从新编译赋给pattip

先是用person替换了man,而后从新定义patt正则,加了wo ,以后再次替换,这样man和woman都被替换掉了,其实能够直接写/(wo)?man/g这个正则,就能所有替换了。字符串

 

    2.RegExpObject.exec(string)string

    这个方法用于检索字符串中的正则表达式的匹配。匹配成功有值的话返回一个数组,里头存放匹配的结果,若是没找到匹配项则返回null.

var str = "Visit W3School"; 
var patt = new RegExp("W3School","g");
console.log(patt.exec(str))

  输出:["W3School"]

在str字符串中查找patt正则定义字符串,找到返回字符串数组

 

    3.RegExpObject.test(string)

    test方法跟exec的区别就是返回值不一样,exec找到返回值数组,test找到返回true,没找到返回false

var str = "Visit W3School";
var patt1 = new RegExp("W3School");
console.log(patt1.test(str))

  输出:true

相关文章
相关标签/搜索