JS中正则表达式

目录

认识正则表达式

正则表达式实例方法

元字符


认识正则表达式

概念:正则表达式是由字符序列形成的、用于匹配字符序列的组合模式

创建:(两种创建方式)

        1.字面量(直接量)

// /正则表达式/修饰符;
var reg = /hello/g;

        2.构造函数

//new RegExp("正则表达式","修饰符")
var reg =new RegExp("hello","g");

修饰符

i:ignoreCase,匹配时忽视大小写

m:multiline,多行匹配

g:global,全局匹配

正则表达式实例方法

exec()

eg:

   const reg = new RegExp("hello","img")
    ceshi = 'hello world'
    console.log(reg.exec(ceshi));//[ 'hello', index: 0, input: 'hello world', groups: undefined ]

返回值: [匹配的内容,index: 在str中匹配的起始位置,input: 参数字符串,groups: undefined]                  否则返回Null       

text()

eg:

 const reg = new RegExp("hello","img")
    ceshi = 'hello world'
    console.log(reg.test(ceshi));//true

返回值:true/false

匹配到则返回true,匹配不到返回false

元字符

数量词:X*表示重复0次或多次

var reg = new RegExp(/^a*$/);
console.log(reg.test("a")); // true
console.log(reg.test("")); // true

X+表示重复至少一次

var reg2 = new RegExp(/^a+$/);
console.log(reg2.test("a")); // true
console.log(reg2.test("")); // false

X?表示重复0或1次

// ? 只允许a出现1次或0次
var reg3 = new RegExp(/^a?$/);
console.log(reg3.test("a")); // true
console.log(reg3.test("")); // true
console.log(reg3.test("aaa")); // false

{n}表示重复n次

// {3} 允许重复3次
var reg4 = new RegExp(/^a{3}$/);
console.log(reg4.test("a")); // false
console.log(reg4.test("")); // false
console.log(reg4.test("aaa")); // true
console.log(reg4.test("aaaa")); // false

{n,}

// {3,} 允许重复出现3次或3次以上多次
var reg5 = new RegExp(/^a{3,}$/);
console.log(reg5.test("a")); // false
console.log(reg5.test("")); // false
console.log(reg5.test("aaa")); // true
console.log(reg5.test("aaaa")); // true

{n,m}

// {3,6} 允许重复出现3次-6次之间,也就是>=3且<=6
var reg6 = new RegExp(/^a{3,6}$/);
console.log(reg6.test("a")); // false
console.log(reg6.test("aaaa")); // true
console.log(reg6.test("aaaaaa")); // true
console.log(reg6.test("aaaaaaa")); // false

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值