正则表达式方法

本文深入探讨了JavaScript中的RegExp对象,重点讲解了test()和exec()方法的使用。test()方法用于检测字符串是否匹配模式,返回true或false;exec()方法则能检索匹配项并返回包含匹配信息的数组。当使用全局匹配标志'g'时,exec()会继续查找后续匹配。这对于理解和应用JavaScript正则表达式至关重要。
摘要由CSDN通过智能技术生成

RegExp对象

创建一个RegExp对象:

var patt=new RegExp(pattern,modifiers);
或更简单的方法
var patt=/pattern/modifiers;
  • pattern表示你要匹配的内容,
  • modifiers表示你匹配的范围及方式

modifiers的取值:(可以两个都选择)

  • i:模糊匹配(不区分大小写);
  • g:全局匹配

正则表达式方法

  • test()

    test() 方法是一个正则表达式方法。
    test() 方法用于检测一个字符串是否匹配某个模式,如果字符串中含有匹配的文本,则返回 true,否则返回 false。
    例子:

let reg=new RegExp('e','')
console.log(reg.test('abcdefg'));  //true
console.log(reg.test('abcd'));     //false
  • exec()
    exec() 方法是一个正则表达式方法。
    exec() 方法用于检索字符串中的正则表达式的匹配。
    该函数返回一个数组,其中存放匹配的结果。如果未找到匹配,返回值为 null。
    数组中的内容:
    [
    pattern,
    index:当前匹配项的位置,
    input:匹配的字符串,
    groups:undefined
    ]

例子:

let reg=new RegExp('e','')
console.log(reg.exec("Th ebst things in life are fre!"));
console.log(reg.exec("Th ebst things in life are fre!"))

//输出结果
[
  'e',
  index: 3,
  input: 'Th ebst things in life are fre!',
  groups: undefined
]
[
  'e',
  index: 3,
  input: 'Th ebst things in life are fre!',
  groups: undefined
]

注意加上全局匹配g之后,会有不一样的变化:

let reg=new RegExp('e','g')
console.log(reg.exec("Th ebst things in life are fre!"));
console.log(reg.exec("Th ebst things in life are fre!"));
console.log(reg.exec("Th ebst things in life are fre!"));

[
  'e',
  index: 3,
  input: 'Th ebst things in life are fre!',
  groups: undefined
]
[
  'e',
  index: 21,
  input: 'Th ebst things in life are fre!',
PS C:\Users\fxk\Desktop\react学习\1.基础学习> node .\23.正则表达式.js
[
  'e',
  index: 3,
  input: 'Th ebst things in life are fre!',
  groups: undefined
]
[
  'e',
  index: 21,
  input: 'Th ebst things in life are fre!',
  groups: undefined
]
[
  'e',
  index: 25,
  input: 'Th ebst things in life are fre!',
  groups: undefined
]

可以看出,当设置为全局匹配之后,就会去后来的内容中匹配。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值