Regex

AI 摘要: 本文介绍了零宽断言的概念和使用方式,包括捕获和非捕获分组以及零宽断言的类型和作用。

内容概述

零宽断言

分类 代码/语法 说明

  • 捕获: (exp) : 匹配exp,并捕获文本到自动命名的组里 (?<name>exp) : 匹配exp,并捕获文本到名称为name的组里,也可以写成(?’name’exp) (?:exp): 匹配exp,不捕获匹配的文本,也不给此分组分配组号
  • 零宽断言:
    (?=exp): 匹配exp前面的位置 (?<=exp) : 匹配exp后面的位置 (?!exp): 匹配后面跟的不是exp的位置 (?<!exp) :匹配前面不是exp的位置
  • 注释
    • (?#comment) 这种类型的分组不对正则表达式的处理产生任何影响,用于提供注释让人阅读

匹配含图片信息的字符串

1
2
3
4
5
// 结果:true (3) ["", "hello", "gif", index: 0, input: "hello.gif", groups: undefined]
reg=/(?=(.*)\.(jpg|png|gif)(?:.*))/; str="hello.gif";  console.log(reg.test(str), str.match(reg))

// 结果: true (4) ["", "hello", "gif", "id=100", index: 0, input: "hello.gif?id=100", groups: undefined]
reg=/(?=(.*)\.(jpg|png|gif)\??(.*))/; str="hello.gif?id=100";  console.log(reg.test(str), str.match(reg))

匹配不含静态资源的字符串

非这几个字符串开头的域名

1
https://(?!(res|hm|zz|client))