JavaScript中的每个正则表达式都是一个对象,同其他的对象一样。RegExp对象还有一些属性,RegExp实例和构造函数都有属性和方法。两者的属性在创建模式和进行测试的时候都会发生改变。
(一) 实例属性
RegExp的实例有一些开发人员可以使用的属性:
global——Boolean值,表示g(全局选项)是否已设置。
ignoreCase——Boolean值,表示i(忽然大小写选项)是否已设置。
lastIndex——整数,代表下次匹配将会从哪个字符位置开始(只有当使用exec()或test()函数才会填入,否则为0)。
multiline——Boolean值,表示m(多行模式选项)是滞已设置。
source——正则表达式的源字符串形式。例如,表达式/[ba]*/的source将返回*[ba]*。
一般不会使用global、ignoreCase、multiline和source属性,因为一般之前就已知道了这些数据:
var reTest=/[ba]*/i;
alert(reTest.global); //outpus “false”
alert(reTest.ignoreCase); //outpus “true”
alert(reTest.multiline); //outpus “false”
alert(reTest.source); //outpus “[ba]*”
真正有用的属性是lastIndex,它可以告诉你正则表达式在某个字符串中停止之前,查找了多远:
var sToMatch=”bbq is shrot for barbecue”;
var reB=/b/g;
alert(reB.lastIndex); //outpus “1”
reB.exec(sToMatch);
alert(reB.lastIndex); //outpus “2”
reB.exec(sToMatch);
alert(reB.lastIndex); //outpus “18”
在这个例子中,正则表达式reB查找的是b。它当首次检测sToMatch时,它发现在第一个位置——也就是位置0——是b;因此lastIndex属性就被设置成1,而再次调用exec()时就从这个地方开始执行。再次调用exec(),表达式在位置1又发现了b,于是将lastIndex设置为2。第三次调用时,发现b在位置17,于是又将lastIndex设置为18。
(二) 静态属性
静态的RegExp属性对所有的正则表达式都有效。这些属性也都与众不同的,因为它们都有两个字句:一个复杂名字和一个以美元符号开关的简短名字。下表中列出了这些属性:
这些属性可以告诉你,关于刚使用exec()和test()完成的匹配的一些特定信息。例如:
var sToMatch=”this has been a short , short summer”;
var reShort=/(s)hort/g;
reShort.test(sToMatch);
alert(RegExp.input);
alert(RegExp.leftContext); //outputs “this has been a short,short summer”
alert(RegExp.rightContext); //outputs “this has been a”
alert(RegExp.lastMatch); //outputs “,short summer”
alert(RegExp.lastMatch); //outputs “short”
alert(RegExp.lastParen); //outputs “s”
这一个例子描述了几个不贩属性应该如何使用:
input属性总是等于测试用的字符串。
RegExp.leftContext包含第一个实例 “short”之前的所有字符,同时RegExp.rightContext包含第一个实例”short”之后的所有字符。
lastMatch的属性包含最后匹配整个正则表达式的字符串,这里就是”short”。
lastParen属性包含最后匹配的分组,这里就是”s”。
也可以使用这些属性的短名字,不过对其中的大部分必须使用方括号标记,因有这些名字在ECMAScript的语法中是不合法的。
var sToMatch=”this has been a short, short summer”;
var reShort=/(s)hort/g;
reShort.test(sToMatch);
alert(RegExp.$_); //outputs “this has been a short, short summer”
alert(RegExp.[“$`”]); //outputs “this has been a”
alert(RegExp.[“$’”]); //outputs “, short summer”
alert(RegExp.[“$&”]); //outputs “short”
alert(RegExp.[“$+”]); //outputs “s”
每次执行exec()和test()时,所有的属性(除multiline外)都会被重新设置。multiline属性在这里不同于其他属性,因为它不依赖最后一次执行的匹配。相反,它可以设置所有的正则表达式的m选项。
var sToMatch=”First second\nthird fourth\nfifth sisxth”
var reLastWordOnLine=/(\w+)$/g;
RegExp.multiline=true;
var arrWords=sToMatch.match(reLastWordOnLine);
这段代码执行结束后,arrWords包含”second”,”fourth”和”sisth”,就像m选项已在表达式中设置过一样。