var expression = /pattern/flags ;
pattern: 任何简单或复杂的正则表达式。
flags: 可以是 g,i,m 或它们的组合。
g:表示全局模式,即模式将被应用于所有字符串,而非在发现第一个匹配项时就立即停止。
i:表示不区分大小写。
m:表示多行,及在到达一行文本末尾时还会继续查找下一行。
例子:
匹配字符串中所有有"at"的实例
var pattern1=/at/g
元字符: ({\^$|)?*+.]}
例子: 匹配所有“.at”, 不区分大小写
var pattern2 = /\.at/gi
exec() : 接受一个参数,即要应用模式的字符串,然后返回包含第一个匹配项信息的数组,或者没有匹配项的情况下返回null.返回的数组虽然是Array 的实例,但包含两个额外的属性:index和input。其中index表示匹配项在字符串中的位置,而input表示应用正则表达式的字符串。
在数组中,第一项是与整个模式匹配的字符串。其它项是与模式中的捕获组匹配的字符串。如果没有捕获组,数组只有一项。
例子:
var text =“mom and dad and body"
var parrern =/mom( and dad( and bady)?)?/gi
var matches = parrern.exec(text);
alert(matches.index); //0
alert(matches.input); //“mom and dad and body"
alert(matches[0]); //“mom and dad and body"
alert(matches[1]); //" and dad and bady"
alert(match[2]); //" and bady"
对于exec()方法而言,即使在模式中设置了全局标志(g),它每次也只会返回一个匹配项。在不设置全局标志的情况下,在同一字符串上调用exec()将始终返回第一个匹配项的信息。而设置全局标志情况下,每次调用exec()则会在字符串中继续查找新的匹配项。
例子:
var text ="cat , bat, sat, fat";
var pattern1 =/.at/; //非全局模式
var matches = pattern1.exec(text);
alert(matches.index); //0
alert(matches[0]); //cat
alert(pattern1.lastIndex); //0
matches = pattern1.exec(text);
alert(matches.index); //0
alert(matches[0]); //cat
alert(pattern1.lastIndex); //0
var pattern2 =/.at/g; //全局模式
var matches = pattern2.exec(tex