语法:
var = /pattern/flags ;
pattern: 任何简单或复杂的正则表达式。
flags: 可以是 g,i,m 或它们的组合。
g:表示全局模式,即模式将被应用于所有字符串,而非在发现第一个匹配项时就立即停止。
i:表示不区分大小写。
m:表示多行,及在到达一行文本末尾时还会继续查找下一行。
例子:
匹配字符串中所有有\"at\"的实例
var pattern1=/at/g
模式中的所有元字符都必须转义。
元字符: ({\\^$|)?*+.]}
例子: 匹配所有“.at”, 不区分大小写
var pattern2 = /\\.at/gi
RegExp 实例方法:
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(text);
alert(matches.index); //0
alert(matches[0]); //cat
alert(pattern2.lastIndex); //3
matches = pattern2.exec(text);
alert(matches.index); //5
alert(matches[0]); //bat
alert(pattern2.lastIndex); //8
正则表达式的第二个方法是 test(), 它接受一个字符串参数,在模式与该参数匹配的情况下返回true;否则返回false. 在只想知道目标字符串与模式是否匹配时很方便。
RegExp 构造函数属性
RegExp 构造函数包含一些属性,这些属性适用于作用域中的所有正则表达式,并且基于所执行的最近一次正则表达式操作而变化。
| 属性名 | 说明 |
| input | 最近一次要匹配的字符串 |
| lastMatch | 最近一次的匹配项 |
| lastParen | 最近一次匹配的捕获组 |
| leftContext | input字符串中lastMatch之前的文本 |
| multiline |
布尔值,表示是否所有表达式都是多行模式 |
| rightContext |
input字符串中lastMatch之后的文本 |
使用这些属性可以从exec()或test()执行的操作中提取出更具体的信息.
例子:
var text =\"this has been a short summer\";
var pattern = /(.)hort/g;
if(pattern.test(text)){
alert(RegExp.input); //this has been a short summer
alert(RegExp.leftContext); //this has been a
alert(RegExp.rightContext); //summer
alert(RegExp.lastMatch): //short
alert(RegExp.lastParen): //s
alert(RegExp.multiline): //false
}
继续阅读与本文标签相同的文章
-
好程序员web前端学习路线分享css3中的渐进增强和降级
2026-05-19栏目: 教程
-
什么是苹果iOS超级签名源码系统?
2026-05-19栏目: 教程
-
好程序员web前端学习路线分享模拟JavaScript中面向对象技术
2026-05-19栏目: 教程
-
WdCP安装和建站教程
2026-05-19栏目: 教程
-
好程序员分享java8新特性之Lambda表达式
2026-05-19栏目: 教程
