compile(string regex, string flags):预编译正则表达式以使其运行更快,经过测试的确预先编译后效率有明显提升。regex参数为正则表达式,flags可以为以下3个值的组合: g – 全局搜索,我的试验结果是不加g标志就只能匹配第一个符合条件的字符串 i – 忽略大小写 m – 多行搜索,似乎默认已经是多行搜索了
index:字符串中第一个匹配表达式的位置,初始为-1
input:正则表达式的匹配目标,注意是只读的
lastIndex:下一个匹配表达式的位置,原话是(Returns the character position where the next match begins in a searched string.)也不知道有没有翻译错,这个属性我没有用到。
lastMatch:最后一个匹配表达式的字符串
lastParen:最后一个匹配的子匹配串,比如正则表达式里有多个以()分组的匹配项,lastParen表示最后一组所匹配的结果
leftContext:从目标字符串的开头到last match的起始位置的所有字符。
rightContext:从last match的结束位置到整个目标字符串的结束位置的所有字符。
$1…$9:表示第n组匹配的结果,这个在正则表达式里有多个以()分组时有用
function matchDemo()
{
var s;
var re = new RegExp("d(b+)(d)","ig");
var str = "cdbBdbsbdbdz";
var arr = re.exec(str);
s = "$1 contains: " + RegExp.$1 + "\n";
s += "$2 contains: " + RegExp.$2 + "\n";
s += "$3 contains: " + RegExp.$3;
return(s);
}
function RegExpTest()
{
var ver = Number(ScriptEngineMajorVersion() + "." + ScriptEngineMinorVersion())
if (ver >= 5.5){
var src = "The rain in Spain falls mainly in the plain.";
var re = /\w+/g;
var arr;
while ((arr = re.exec(src)) != null)
print(arr.index + "-" + arr.lastIndex + "\t" + arr);
}
else{
alert("You need a newer version of JScript for this to work");
}
}
function matchDemo()
{
var s; //Declare variable.
var re = new RegExp("d(b+)(d)","ig"); //Regular expression pattern.
var str = "cdbBdbsbdbdz"; //String to be searched.
var arr = re.exec(str); //Perform the search.
s = "$1 returns: " + RegExp.$1 + "\n";
s += "$2 returns: " + RegExp.$2 + "\n";
s += "$3 returns: " + RegExp.$3 + "\n";
s += "input returns : " + RegExp.input + "\n";
s += "lastMatch returns: " + RegExp.lastMatch + "\n";
s += "leftContext returns: " + RegExp.leftContext + "\n";
s += "rightContext returns: " + RegExp.rightContext + "\n";
s += "lastParen returns: " + RegExp.lastParen + "\n";
return(s); //Return results.
}
document.write(matchDemo());