前端系列:正则表达式RegExp详解

文章目录

    • 正则创建
    • 匹配方法
    • 元字符
    • 字符集合
    • 边界
    • 分组
    • 数量词汇
    • 匹配模式
    • RegExp 方法特性

正则创建

  • 字面量创建

    const str = 'asdf123sds3234'
    const regexp = /\d+/g
    const res = str.match(regexp)
    console.log(res) //['123', '3234']
    
  • 构造函数

    const str = 'asdf123asad23121'
    const regexp = new RegExp('\\d+', 'g')
    const res = str.match(regexp)
    console.log(res) // ['123', '23121']
    

匹配方法

  • 字符串方法

    • match:返回一个字符串匹配正则表达式的结果,如果未找到匹配则为null

      const str = 'asdf123sds3234'
      const regexp = /\d+/g
      const res = str.match(regexp)
      console.log(res) //['123', '3234']
      
    • search:返回正则表达式在字符串中首次匹配项的索引;否则,返回 -1

      const str = 'as12121es121sd'
      const regexp = /\d+/
      const res = str.search(regexp)
      console.log(res) // 2
      
    • replace:返回一个由替换值(replacement)替换部分或所有的模式(pattern)匹配项后的新字符串。模式可以是一个字符串或者一[正则表达式],替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。如果pattern是字符串,则仅替换第一个匹配项

      const str = 'asahsashhuihui12332467y7'
      const regexp = /(hui)|(123)/g
      const res = str.replace(regexp, '*')
      console.log(res) //asahsash***32467y7
      const res2 = str.replace(regexp, (arg) => {return '*'.repeat(arg.length)
      })
      console.log(res2) //asahsash*********32467y7
      
    • split:方法使用指定的分隔符字符串将一个String对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置

      const str = 'cccasdfgd9asasdsa12121'
      const regexp = /a/
      const res = str.split(regexp)
      console.log(res) //['ccc', 'sdfgd9', 's', 'sds', '12121']
      
  • 正则对象方法

    • test:执行一个检索,用来查看正则表达式与指定的字符串是否匹配。返回 truefalse

      let str = 'asdhadhjkhjk12323879789pjdhjfhj'
      let regexp = /\d+/
      let res = regexp.test(str)
      console.log(res) // true
      regexp = /m/
      res = regexp.test(str)
      console.log(res) // false
      
    • exec:方法在一个指定字符串中执行一个搜索匹配。返回一个结果数组或 null

      let str = 'sfkdhjk12238jks544jk'
      let regexp = new RegExp('\\d+', 'g')
      let res = regexp.exec(str)
      console.log(res) //['12238', index: 7, input: 'sfkdhjk12238jks544jk', groups: undefined]
      res = regexp.exec(str)
      console.log(res) //['544', index: 15, input: 'sfkdhjk12238jks544jk', groups: undefined]
      

元字符

  • . :匹配默认除(\n,\r,\u2028,\u2029)之外的任何单个字符

    const str = 'adad12121dfe234s'
    const regexp = /./
    const res = str.replace(regexp, '*')
    console.log(res) //*dad12121dfe234s
    
  • \ :转义符,它有两层含义

    • 表示下一个具有特殊含义的字符为字面值

    • 表示下一个字符具有特殊含义(转义后的结果是元字符内约定的)

    const str = 'sdsds/dfdfd12121'
    const regexp = /\/d/
    const res = regexp.test(str)
    console.log(res) //true
    
  • \d :匹配任意一个阿拉伯数字的字符

    const str = 'xsdsd3121xcxx12121cx'
    const regexp = /\d+/
    const res = regexp.exec(str)
    console.log(res) //['3121', index: 5, input: 'xsdsd3121xcxx12121cx', groups: undefined]
    
  • \D :匹配任意一个非阿拉伯数字的字符

    const str = 'xsdsd3121xcxx12121cx'
    const regexp = /\D+/
    const res = regexp.exec(str)
    console.log(res) //['xsdsd', index: 0, input: 'xsdsd3121xcxx12121cx', groups: undefined]
    
  • \w :匹配任意一个(字母、数字、下划线)的字符

    const str = '@qwqwq_asas12121df0df0l;ll'
    const regexp = /\w+/g
    const res = str.match(regexp)
    console.log(res) //['qwqwq_asas12121df0df0l', 'll']
    
  • \W :匹配任意一个非(字母、数字、下划线)的字符

    const str = '@qwqwq_asas12121df0df0l;ll'
    const regexp = /\W+/g
    const res = str.match(regexp)
    console.log(res) //['@', ';']
    
  • \s :匹配一个空白符,包括空格、制表符、换页符、换行符和其他的Unicode 空格

    const str = 'sdhjk\n\rsdsd\n'
    const regexp = /\s+/g
    const res = str.replace(regexp, '-')
    console.log(res) //sdhjk-sdsd-
    
  • \S :匹配一个非空白符

    const str = 'sdhjk\n\rsdsd\n'
    const regexp = /\S+/g
    const res = str.match(regexp)
    console.log(res) //['sdhjk', 'sdsd']
    
  • \t :匹配一个水平制表符(horizontal tab)

    const str = 'sdhjk\tsdsd'
    const regexp = /\t/
    const res = regexp.test(str)
    console.log(res) //true
    
  • \r :匹配一个回车符(carriage return)

    const str = 'sdhjk\rsdsd'
    const regexp = /\r/
    const res = regexp.test(str)
    console.log(res) //true
    
  • \n :匹配一个换行符(linefeed)

    const str = 'sdhjk\nsdsd'
    const regexp = /\n/
    const res = regexp.test(str)
    console.log(res) //true
    
  • \v :匹配一个垂直制表符(vertical tab)

    const str = 'sdhjk\vsdsd'
    const regexp = /\v/
    const res = regexp.test(str)
    console.log(res) //true
    
  • \f :匹配一个换页符(form-feed)

    const str = 'sdhjk\fsdsd'
    const regexp = /\f/
    const res = regexp.test(str)
    console.log(res) //true
    

字符集合

  • [xyz] :一个字符集合。匹配方括号中的任意字符,包括转义序列。你可以使用破折号(-)来指定一个字符范围。对于点(.)和星号(*)这样的特殊符号在一个字符集中没有特殊的意义。他们不必进行转义,不过转义也是起作用的

    const str = 'dfgd12312df57676ds'
    const regexp = /[1-9]+/g
    const res = str.match(regexp)
    console.log(res) //['12312', '57676']
    
  • [^xyz] :一个反向字符集。也就是说, 它匹配任何没有包含在方括号中的字符。你可以使用破折号(-)来指定一个字符范围。任何普通字符在这里都是起作用的

    const str = 'dfgd12312df57676ds'
    const regexp = /[^1-9]+/g
    const res = str.match(regexp)
    console.log(res) //['dfgd', 'df', 'ds']
    
  • [\b] :匹配一个退格(backspace)。(不要和\b 混淆了。)

    const str = `dfgd12312df\b57676ds`
    const regexp = /[\b]/g
    const res = str.match(regexp)
    console.log(res) //['\b']
    

边界

  • ^ :匹配输入的开始。如果多行标志被设置为 true,那么也匹配换行符后紧跟的位置

    const str = `sds234fsd\nsd4345ds\nsqwq`
    const regexp = /^sd.*/gm
    const res = str.match(regexp)
    console.log(res) //['sds234fsd', 'sd4345ds']
    
  • $ :匹配输入的结束。如果多行标志被设置为 true,那么也匹配换行符前的位置

    const str = `sds234fsd\nsd4345ds\nsqwq`
    const regexp = /^sd.*d$/gm
    const res = str.match(regexp)
    console.log(res) //['sds234fsd']
    
  • \b :匹配一个词的边界。一个词的边界就是一个词不被另外一个“字”字符跟随的位置或者前面跟其他“字”字符的位置,例如在字母和空格之间。注意,匹配中不包括匹配的字边界。换句话说,一个匹配的词的边界的内容的长度是 0。(不要和[\b]混淆了)

    const str = `this is dog`
    const regexp = /\bi/
    const res = str.match(regexp)
    console.log(res) //['i', index: 5, input: 'this is dog', groups: undefined]
    
  • \B :匹配一个非单词边界

    const str = `this is dog`
    const regexp = /[a-z]+\Bi[a-z]+/
    const res = str.match(regexp)
    console.log(res) //['this', index: 0, input: 'this is dog', groups: undefined]
    

分组

  • () :对表达式进行分组,类似数学中的分组,也称为子项

    • 索引分组:(x)

      const str = 'asabvb\r121ghjsdhj sdsds'
      const regexp = /(\w+)\r(\w+)/
      const res = str.match(regexp)
      console.log(res) //['asabvb\r121ghjsdhj', 'asabvb', '121ghjsdhj', index: 0, input: 'asabvb\r121ghjsdhj sdsds', groups: undefined]
      
    • 命名分组:(?),groups 属性

      const str = 'asabvb\r121ghjsdhj sdsds'
      const regexp = /(?<str>\w+)\r(\w+)/
      const res = str.match(regexp)
      console.log(res) //['asabvb\r121ghjsdhj', 'asabvb', '121ghjsdhj', index: 0, input: 'asabvb\r121ghjsdhj sdsds', groups: {str: 'asabvb'}]
      
    • 捕获匹配:(x)

      const str = 'this is dog'
      const regexp = /(this)/
      const res = str.match(regexp)
      console.log(RegExp.$1) //this
      console.log(res) //['this', index: 0, input: 'this is dog', groups: undefined]
      
    • 非捕获匹配:(?:x)

      //简而言之就是不捕获文本 ,也不针对组合计进行计数
      const str = 'this is dog'
      const regexp = /(?:this)/
      const res = str.match(regexp)
      console.log(RegExp.$1) //''
      console.log(res) //['this', index: 0, input: 'this is dog', groups: undefined]
      
    • 断言/预查

      • 正向肯定断言:x(?=y)
      const str = 'iphone8iphone11iphoneNumber'
      const regexp = /iphone(?=\d{1,2})/g
      const res = str.replace(regexp, '苹果')
      console.log(res) //苹果8苹果11iphoneNumber
      
      • 正向否定断言:x(?!y)
      const str = 'iphone8iphone11iphoneNumber'
      const regexp = /iphone(?!\d{1,2})/g
      const res = str.replace(regexp, '苹果')
      console.log(res) //iphone8iphone11苹果Number
      
      • 负向肯定断言
      const str = '10px20px30pxxpx'
      const regexp = /(?<=\d{2})px/g
      const res = str.replace(regexp, '像素')
      console.log(res) //10像素20像素30像素xpx
      
      • 负向否定断言
      const str = '10px20px30pxxpx'
      const regexp = /(?<!\d{2})px/g
      const res = str.replace(regexp, '像素')
      console.log(res) //10px20px30pxx像素
      

数量词汇

  • x{n} :n 是一个正整数,前面的模式 x 连续出现 n 次时匹配

    let str = '123ab_cd123'
    let regexp = /[a-z]{3}/g
    let res = str.replace(regexp, '*')
    console.log(res) //123ab_cd123
    regexp = /[a-z]{2}/g
    res = str.replace(regexp, '*')
    console.log(res) //123*_*123
    
  • x{n,m} :n 和 m 为正整数,前面的模式 x 连续出现至少 n 次,至多 m 次时匹配

    let str = '123ab_cd123'
    let regexp = /[a-z]{1,2}/g
    let res = str.replace(regexp, '*')
    console.log(res) //123*_*123
    regexp = /[a-z]{1,1}/g
    res = str.replace(regexp, '*')
    console.log(res) //123**_**123
    
  • x{n,} :n 是一个正整数,前面的的模式 x 连续出现至少 n 次时匹配

    let str = '123abwasdsd_123'
    let regexp = /[a-z]{1,}/g
    let res = str.replace(regexp, '*')
    console.log(res) //123*_123
    
  • x* :匹配前面的模式 x 0 次或多次,等价于 {0,}

    let str = '123abwasdsd_123'
    let regexp = /123*/g
    let res = str.replace(regexp, '*')
    console.log(res) //*abwasdsd_*
    
  • x+ :匹配前面的模式 x 1 次或多次,等价于 {1,}

    let str = '123abwasdsd_123'
    let regexp = /123+/g
    let res = str.replace(regexp, '*')
    console.log(res) //*abwasdsd_*
    
  • x? :匹配前面的模式 x 0 次或 1 次,等价于 {0,1}

    let str = '123abwasdsd_123'
    let regexp = /d_123?/g
    let res = str.replace(regexp, '*')
    console.log(res) //123abwasds*
    
  • x|y :匹配 x 或 y

    let str = '123abwasdsd_123'
    let regexp = /[A-Z]|[a-z]+/g
    let res = str.replace(regexp, '*')
    console.log(res) //123*_123
    

匹配模式

  • g:全局搜索

    let str = '123abwasdsd_123'
    let regexp = /\d+/
    let res = str.replace(regexp, '*')
    console.log(res) //*abwasdsd_123
    regexp = /\d+/g
    console.log(regexp.global) // true
    res = str.replace(regexp, '*')
    console.log(res) //*abwasdsd_*
    
  • i:不区分大小写搜

    let str = '123abCasdsd_123'
    let regexp = /[a-z]+/g
    let res = str.replace(regexp, '*')
    console.log(res) //123*C*_123
    regexp = /[a-z]+/gi
    console.log(regexp.ignoreCase) // true
    res = str.replace(regexp, '*')
    console.log(res) //123*_123
    
  • m:多行搜索

    let str = `abas
    asds`
    let regexp = /^\w+/gm
    console.log(regexp.multiline) // true
    let res = str.replace(regexp, '*')
    console.log(res) //* *
    
  • s:允许 .匹配换行符

    let str = `<div>hello world</div>`
    let regexp = /<div>.*<\/div>/gs
    console.log(regexp.dotAll)
    let res = regexp.test(str)
    console.log(res) //true
    
  • u:使用 unicode 码的模式进行匹配

    console.log(/^.$/.test('\uD842\uDFB7')) //false
    console.log(/^.$/u.test('\uD842\uDFB7')) //true
    console.log(/^.$/u.unicode) // true
    
  • y:执行“粘性(sticky)”搜索,匹配从目标字符串的当前位置开始

    const str = '121278789s834234dsssdf'
    const regexp = /\d+/gy
    console.log(regexp.sticky)
    console.log(regexp.exec(str)) // ['121278789', index: 0, input: '121278789s834234dsssdf', groups: undefined]
    console.log(regexp.exec(str)) // null
    

RegExp 方法特性

;/a/[Symbol.match]('abc')
;/a/[Symbol.matchAll]('abc')
;/a/[Symbol.replace]('abc', 'A')
;/a/[Symbol.search]('abc')
;/-/[Symbol.split]('a-b-c')
const str = 'asfs1212343sdsds12asa'
let regexp = /\d+/g
regexp.exec(str)
console.log(RegExp.input) //asfs1212343sdsds12asa
console.log(RegExp.$_) //asfs1212343sdsds12asa
console.log(regexp.lastIndex) //11
console.log(RegExp.lastMatch) //1212343
console.log(RegExp['$&']) //1212343
console.log(RegExp.leftContext) //asfs
console.log(RegExp['$`']) //asfs
console.log(RegExp.rightContext) //sdsds12asa
console.log(RegExp["$'"]) //sdsds12asa
regexp = /(\d+)([a-z]+)/g
const res = str.replace(regexp, '$1')
console.log(RegExp.$1) //12
console.log(RegExp.$2) //asa

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/609699.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[②C++ Boost]: Boost库编译,arm交叉编译方法

前言 Boost是十分实用的C库&#xff0c;如果想在arm环境下使用&#xff0c;就需要自己下载源码编译&#xff0c;本篇博客就记录下Boost库的编译方法。 下载Boost源码 Boost源码的下载路径可以使用&#xff1a;https://sourceforge.net/projects/boost/files/boost/ 编译 …

408重要数据结构+算法汇总——C语言手搓版(全)

该套代码&#xff0c;大学期间跟着网课一遍一遍打下来的&#xff0c;408大概就这些了&#xff0c;别的杂七杂八其实还有很多&#xff0c;遗憾的是&#xff0c;一直没有整理和归纳。导致一遍遍地学一遍遍地忘记。大四就快毕业了&#xff0c;研也考了。这里做个整理&#xff0c;算…

JavaScript小案例

烟花 html <body><div id"box"></div><script src"./move.js"></script><script src"./fire.js"></script> </body>js代码 fire.js function Fire(){// 获取box盒子this.box document.que…

虚幻UE 材质-材质编辑器节点2

上一篇&#xff1a;虚幻UE 材质-材质编辑器节点 1 上一篇文章对材质编辑器的部分节点做了讲解和对比较常用的功能做了展示 这篇文章继续对上一篇的文章进行补充 文章目录 前言一、ReflectionVector反射向量二、Material Parameter Collection材质参数集三、TwoSideSign和Vertex…

使用 Process Explorer 和 Windbg 排查软件线程堵塞问题

目录 1、问题说明 2、线程堵塞的可能原因分析 3、使用Windbg和Process Explorer确定线程中发生了死循环 4、根据Windbg中显示的函数调用堆栈去查看源码&#xff0c;找到问题 4.1、在Windbg定位发生死循环的函数的方法 4.2、在Windbg中查看变量的值去辅助分析 4.3、是循环…

uniapp(vue2)+VoerkaI18n多语言

今天我学习了VoerkaI18n国际化插件&#xff0c;它是一个适用于Javascript/Vue/React/Solid/ReactNative的国际化全流程解决方案。VoerkaI18n可以帮助我们轻松地实现应用程序的多语言支持&#xff0c;使得应用程序可以适应不同的语言环境。 比较吸引我的是集成自动翻译,t(“中华…

基于net6的asp.net core webapi项目打包为docker镜像,并推送至私有镜像仓库harbor中

基于net6的asp.net core webapi项目打包为docker镜像&#xff0c;并推送至私有镜像仓库harbor中 0、环境说明1、打包步骤1.1 创建Asp.net core WebApi项目1.2 在Asp.net core WebApi项目根目录下创建Dockerfile文件1.3 在子系统Ubuntu20.04.4中通过docker build生成docker镜像1…

【angular教程240105】02绑定属性 绑定数据、条件判断、加载图片、【ngClass】 【ngStyle】、Angular管道

【angular】02绑定属性 绑定数据、条件判断、加载图片、【ngClass】 【ngStyle】、Angular管道 0 一些基础的概念 标记为可注入的服务 在Angular中&#xff0c;一个服务是一个通常提供特定功能的类&#xff0c;比如获取数据、日志记录或者业务逻辑等。标记为可注入的服务意味着…

PTA——查验身份证

一个合法的身份证号码由17位地区、日期编号和顺序编号加1位校验码组成。校验码的计算规则如下&#xff1a; 首先对前17位数字加权求和&#xff0c;权重分配为&#xff1a;{7&#xff0c;9&#xff0c;10&#xff0c;5&#xff0c;8&#xff0c;4&#xff0c;2&#xff0c;1&am…

判断一个数是NaN和Infinity的方法

1. isNaN()、 Number.isNaN()的区别 isNaN()只要不是数字都会返回true&#xff0c; Number.isNaN()只有NaN才 返回 true 所以&#xff0c;想严格检查一个值是否是 NaN&#xff0c;就选择 Number.isNaN() isNaN() isNaN() 函数会尝试将传入的值转换为数字&#xff0c;然后检查…

PCL 计算异面直线的距离

目录 一、算法原理二、代码实现三、结果展示四、相关链接本文由CSDN点云侠原创,PCL 计算异面直线的距离,爬虫自重。如果你不是在点云侠的博客中看到该文章,那么此处便是不要脸的爬虫与GPT。 一、算法原理 设置直线 A B AB A

在vue3上挂载方法,以及在页面中使用setup语法糖 该怎么使用原型(公共)上的方法

//新建的项目的main.js文件是这样的 //main.js 文件 //befor import { createApp } from vue; import App from ./App.vue;const app createApp(App); app.mount(#app);以下例子用于解释在vue3.0的main.js中挂载公共的方法&#xff08;foo&#xff09; //main.js 文件 //afte…

【JVM 基础】 Java 类加载机制

JVM 基础 - Java 类加载机制 类的生命周期类的加载: 查找并加载类的二进制数据连接验证: 确保被加载的类的正确性准备: 为类的静态变量分配内存&#xff0c;并将其初始化为默认值解析: 把类中的符号引用转换为直接引用 初始化使用卸载 类加载器&#xff0c; JVM类加载机制类加载…

nuxt 不解析HTML结构bug

记录一个本人Vue3迁移Nuxt3的报错 报错信息 [Vue warn]: Failed to resolve directive: top [nitro] [unhandledRejection] TypeError: Cannot read properties of undefined (reading ‘getSSRProps’) 原因是Vue3在迁移到nuxt3的时候有一个自定义指令没有搬过来&#xff0…

flutter 打包安卓apk 常用配置

打包之前需要先不配置不然会报错 Execution failed for task ‘:app:mergeReleaseResources’. APP目录下的build.gradleaaptOptions.cruncherEnabled falseaaptOptions.useNewCruncher false如图 配置targetSdkVersion 、minSdkVersion 在android/app/src目录下的build.…

自承载 Self-Host ASP.NET Web API 1 (C#)

本教程介绍如何在控制台应用程序中托管 Web API。 ASP.NET Web API不需要 IIS。 可以在自己的主机进程中自托管 Web API。 创建控制台应用程序项目 启动 Visual Studio&#xff0c;然后从“开始”页中选择“新建项目”。 或者&#xff0c;从“ 文件 ”菜单中选择“ 新建 ”&a…

【小工具】pixi-live2d-display,直接可用的live2d的交互网页/桌面应用

效果&#xff1a; <script src"https://cubism.live2d.com/sdk-web/cubismcore/live2dcubismcore.min.js"></script> <script src"https://cdn.jsdelivr.net/gh/dylanNew/live2d/webgl/Live2D/lib/live2d.min.js"></script> <…

CCSC,一种CPU架构

core-circuit-separate-computer 核与执行电路的分离&#xff0c;最初是为了省电。 用寄存器实现这种分离。 V寄存器控制着执行电路的供电&#xff0c;V0则不供电&#xff0c;进入省电模式&#xff1b;V1则供电&#xff0c;进入工作模式。 P寄存器是parameter-register&#xf…

4.【TypeScript 教程】TypeScript BigInt

TypeScript BigInt 本节介绍的 bigint 数据类型是用来表示那些已经超出了 number 类型最大值的整数值&#xff0c;对于总是被诟病的整数溢出问题&#xff0c;使用了 bigint 后将完美解决。 1. 解释 bigint 是一种基本数据类型&#xff08;primitive data type&#xff09;。 …

算法练习:查找二维数组中的目标值

题目&#xff1a; 编写一个高效的算法来搜索矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性&#xff1a;每行的元素从左到右升序排列。每列的元素从上到下升序排列。 实现&#xff1a; 1. main方法 public static void main(String[] args) {int[][] matrix {{1…