RegExp实例方法和字符串的模式匹配方法的总结

RegExp实例方法

ECMAScript通过RegExp类型来支持正则表达式,创建正则表达式有两种方式:

//使用字面量形式定义正则表达式
var pattern1 = /[bc]at/i

//使用构造函数创建
var pattern2 = new RegExp("[bc]at", "i")

//构造函数接受两个参数:要匹配的字符串模式和可选的标志字符串

ECMAScript3中正则表达式字面量始终会共享同一个RegExp实例,而使用构造函数创建的每一个新RegExp实例都是一个新实例。ECMAScript5明确规定,使用正则表达式字面量必须像直接调用RegExp构造函数一样每次都创建新的RegExp实例,故两种创建方式无区别,使用哪一个都无所谓。

exec()方法:接受要应用模式的字符串为参数,返回包含第一个匹配项信息的数组;或者在没有匹配项的情况下返回null。返回到数组是Array的实例。

      返回的数组包含两个额外的属性:index和input。其中,index表示匹配项在字符串中的位置,input表示应用正则表达式的字符串。在数组中,第一项是与整个模式匹配的字符串,其他项是与模式中的捕获组匹配的字符串。

var text = "mom and dad and baby";
var pattern = /mom( and dad( and baby)?)?/gi;
var matches = pattern.exec(text);

alert(matches.index);    //0
alert(matches.input);    //"mom and dad and baby"
alert(matches[0]);       //"mom and dad and baby"
alert(matches[1]);       //" and dad and baby"
alert(matches[2]);       //" and baby"

test()方法:接受一个字符串参数。在模式与该参数匹配的情况下返回true,否则返回false 。

var text = “000-00-0000”;
var pattern = /d{3}-d{2}-d{4}/;

pattern.test(text);           //true

compile()方法:接收一个字符串参数,用来改变正则表达式的模式匹配值。

var pattern = /abc/;
pattern.test("abc");    //true

pattern.compile("def");
pattern.test("abc");    //false
pattern.test("def");    //true

字符串模式匹配方法

match()方法:接受一个参数(正则表达式或者RegExp对象)。返回一个数组,在数组中,第一项是与整个模式匹配的字符串,其他项是与正则表达式中的捕获组匹配的字符串。

        (与RegExp对象的exec()方法得到的结果相同)

var text = "cat, bat, sat, fat"; 
var pattern = /.at/;

var matches = text.match(pattern);        
alert(matches.index);        //0
alert(matches[0]);           //"cat"
alert(pattern.lastIndex);    //0

search()方法:接受一个参数(正则表达式或者RegExp对象)。返回字符串中第一个匹配项的索引,没有找到则返回-1。始终是从字符串开头向后查找模式。

var text = "cat, bat, sat, fat";

var pos = text.search(/at/);
alert(pos);   //1

replace()方法:接受两个参数(第一个参数可以是一个RegExp对象或者是一个字符串(这个字符串不会转换为正则表达式),第二个参数可以是一个字符串或者一个函数)

var text = "cat, bat, sat, fat"; 

var result = text.replace("at", "ond");
alert(result);    //"cond, bat, sat, fat"

result = text.replace(/at/g, "ond");
alert(result);    //"cond, bond, sond, fond"

split()方法:接受两个参数(第一个参数可以是一个RegExp对象或者是一个字符串(这个字符串不会转换为正则表达式),第二个参数可选,用于指定返回的数组的大小)

      基于指定的分隔符将一个字符串分割成多个子字符串,并将结果放在一个数组中。

var colorText = "red,blue,green,yellow";

var colors1 = colorText.split(",");      //["red", "blue", "green", "yellow"]
var colors2 = colorText.split(",", 2);   //["red", "blue"]
var colors3 = colorText.split(/[^\,]+/); //["", ",", ",", ",", ""]
/[^\,]+/  表示不是逗号的连续字符
原文地址:https://www.cnblogs.com/guorange/p/6693605.html