美文网首页
RegExp实例

RegExp实例

作者: Leaf_Ysm | 来源:发表于2018-11-20 11:22 被阅读0次
exec() 方法用于检索字符串中的正则表达式的匹配。

exec()接受一个参数,既要应用模式的字符串,然后返回包含第一个匹配项信息的数组;或者在没有匹配项的情况下返回null;

exec()即使在模式中设置了全局模式(g),也只返回一个匹配项
在不设置全局模式下,在同一个字符串上多次调用exec()将始终返回第一匹配信息;在设置全局模式下,每次调用exec()则会在字符串中继续查找新匹配项。

举个例子看一下(模式没有设置全局模式):
var text = "cat, bat, sat, fat,aaa";
var pattern1 = /.at/;
var matches = pattern1.exec(text);
 console.log(matches.index); //0
 console.log(matches[0]); //cat
 console.log(matches.input); //cat, bat, sat, fat,aaa
 console.log(pattern1.lastIndex);//0
 matches = pattern1.exec(text);
 console.log(matches.index);//0
 console.log(matches[0]);//cat
 console.log(matches.input);//cat, bat, sat, fat,aaa
 console.log(pattern1.lastIndex);//0
举另一个例子看一下(模式设置全局模式):
var text = "cat, bat, sat, fat,aaa";
var pattern1 = /.at/g; //设置了全局模式
var matches = pattern1.exec(text);
 console.log(matches.index); //0
 console.log(matches[0]); //cat
 console.log(matches.input); //cat, bat, sat, fat,aaa
 console.log(pattern1.lastIndex);//3
 matches = pattern1.exec(text);
 console.log(matches.index);//5
 console.log(matches[0]);//bat
 console.log(matches.input);//cat, bat, sat, fat,aaa
 console.log(pattern1.lastIndex);//8

以上例子中还用到 lastIndex 方法, 这里简单讲解一下,这个方法会返回下一个搜索匹配想的字符位置;

除了exec()方法,正则表达式还提供了test()方法;
test()接受一个字符串,在匹配成功时,返回true,失败时,返回false;所以这个方法常用在if语句中;

相关文章

  • RegExp对象

    正则定义 也可以使用构造函数RegExp()定义 RegExp实例属性 RegExp实例方法 exec()方法 R...

  • mysql的正则表达式

    regexp '^a' 表示以a开头regexp ‘a$’ 表示以a结尾regexp ' a'表示包含a实例...

  • RegExp实例

    exec() 方法用于检索字符串中的正则表达式的匹配。 exec()接受一个参数,既要应用模式的字符串,然后返回包...

  • JS正则表达式详解

    RegExp对象实例化 RegExp是JS的正则表达式对象,实例化一个RegExp对象有字面量和构造函数2种方式。...

  • 2018-11-15

    打卡时间:15:30-16:0021:40-22:40 RegExp实例属性 RegExp的每个实例都具有下列属性...

  • js高级程序设计笔记12

    RegExp实例方法 1.exec()

  • 第五章 RegExp类型

    简述 RegExp实例方法exec()test() RegExp构造函数属性 简述 正则表达式由普通字符(例如:字...

  • Convert Object to Number

    1.Object 2.Array 3.Function 4.Date 5.RegExp 实例1 实例2 实例3

  • 正则表达式:从Copy到手写

    1. RegExp对象 JavaScript有两种方式实例化RegExp对象 字面量 构造函数 字面量 构造函数 ...

  • 学会正则表达式

    一、RegExp 对象 JavaScript 通过内置对象 RegExp 支持正则表达式有两种方法实例化 RegE...

网友评论

      本文标题:RegExp实例

      本文链接:https://www.haomeiwen.com/subject/wfetqqtx.html