js基础速成12-正则表达式

news2024/10/9 8:13:19

正则表达式

正则表达式(Regular Expression)或 RegExp 是一种小型编程语言,有助于在数据中查找模式。RegExp 可以用来检查某种模式是否存在于不同的数据类型中。在 JavaScript 中使用 RegExp,可以使用 RegExp 构造函数,或者使用两个斜杠后跟一个标志来声明 RegExp 模式。我们可以通过两种方式创建模式。

声明字符串时,我们使用单引号、双引号或反引号;声明正则表达式时,我们使用两个斜杠和一个可选的标志。标志可以是 g、i、m、s、u 或 y。

RegExp 参数

正则表达式接受两个参数。一个是必需的搜索模式,另一个是可选的标志。

模式

模式可以是文本或任何具有某种相似性的模式。例如,电子邮件中的“spam”一词可以是我们感兴趣的模式,或者电话号码的格式可能是我们想要查找的。

标志

标志是正则表达式中的可选参数,决定了搜索的类型。让我们看看一些标志:

  • g:全局标志,表示在整个文本中查找模式
  • i:不区分大小写标志(它会搜索小写和大写)
  • m:多行

使用 RegExp 构造函数创建模式

声明不带全局标志和不区分大小写标志的正则表达式。

// 不带标志
let pattern = 'love'
let regEx = new RegExp(pattern)

声明带有全局标志和不区分大小写标志的正则表达式。

let pattern = 'love'
let flag = 'gi'
let regEx = new RegExp(pattern, flag)

使用 RegExp 对象声明正则模式。在 RegExp 构造函数内编写模式和标志。

let regEx = new RegExp('love','gi')

不使用 RegExp 构造函数创建模式

声明带有全局标志和不区分大小写标志的正则表达式。

let regEx= /love/gi

上述正则表达式与我们使用 RegExp 构造函数创建的相同。

let regEx= new RegExp('love','gi')

RegExp 对象方法

让我们看看一些 RegExp 方法。

测试匹配

test():测试字符串中是否存在匹配项。返回 true 或 false。

const str = 'I love JavaScript'
const pattern = /love/
const result = pattern.test(str)
console.log(result)
true
包含所有匹配的数组

match():返回一个包含所有匹配项的数组,包括捕获组,如果没有找到匹配则返回 null。
如果不使用全局标志,match() 返回一个包含模式、索引、输入和组的数组。

const str = 'I love JavaScript'
const pattern = /love/
const result = str.match(pattern)
console.log(result)
["love", index: 2, input: "I love JavaScript", groups: undefined]
const str = 'I love JavaScript'
const pattern = /love/g
const result = str.match(pattern)
console.log(result)
["love"]

search():在字符串中测试匹配。返回匹配的索引,或如果搜索失败则返回 -1。

const str = 'I love JavaScript'
const pattern = /love/g
const result = str.search(pattern)
console.log(result)
2
替换子字符串

replace():在字符串中搜索匹配项,并将匹配的子字符串替换为替换字符串。

const txt = 'Python is the most beautiful language that a human begin has ever created.\
I recommend python for a first programming language'

matchReplaced = txt.replace(/Python|python/, 'JavaScript')
console.log(matchReplaced)
JavaScript is the most beautiful language that a human begin has ever created.I recommend python for a first programming language
const txt = 'Python is the most beautiful language that a human begin has ever created.\
I recommend python for a first programming language'

matchReplaced = txt.replace(/Python|python/g, 'JavaScript')
console.log(matchReplaced)
JavaScript is the most beautiful language that a human begin has ever created.I recommend JavaScript for a first programming language
const txt = 'Python is the most beautiful language that a human begin has ever created.\
I recommend python for a first programming language'

matchReplaced = txt.replace(/Python/gi, 'JavaScript')
console.log(matchReplaced)
JavaScript is the most beautiful language that a human begin has ever created.I recommend JavaScript for a first programming language
const txt = '%I a%m te%%a%%che%r% a%n%d %% I l%o%ve te%ach%ing.\
T%he%re i%s n%o%th%ing as m%ore r%ewarding a%s e%duc%at%i%ng a%n%d e%m%p%ow%er%ing \
p%e%o%ple.\
I fo%und te%a%ching m%ore i%n%t%er%%es%ting t%h%an any other %jobs.\
D%o%es thi%s m%ot%iv%a%te %y%o%u to b%e a t%e%a%cher.'

matches = txt.replace(/%/g, '')
console.log(matches)  
I am teacher and  I love teaching.There is nothing as more rewarding as educating and empowering people.I found teaching more interesting than any other jobs.Does this motivate you to be a teacher.
  • []:一组字符
    • [a-c] 表示 a 或 b 或 c
    • [a-z] 表示任何字母 a 到 z
    • [A-Z] 表示任何字符 A 到 Z
    • [0-3] 表示 0 或 1 或 2 或 3
    • [0-9] 表示任何数字 0 到 9
    • [A-Za-z0-9] 表示任何 a 到 z、A 到 Z、0 到 9 的字符
  • \:用于转义特殊字符
    • \d 表示匹配字符串中包含数字(0-9)
    • \D 表示匹配字符串中不包含数字
  • .:除了换行符 (\n) 之外的任何字符
  • ^:以…开头
    • /^substring/ 例如 /^love/,表示以“love”开头的句子
    • /[^abc]/ 表示不是 a、不是 b、不是 c
  • $:以…结尾
    • /substring / 例如 / l o v e / 例如 /love /例如/love/,表示以“love”结尾的句子
  • *:零次或多次
    • /[a]*/ 表示 a 是可选的,或者可以出现多次
  • +:一次或多次
    • /[a]+/ 表示至少出现一次或多次
  • ?:零次或一次
    • /[a]?/ 表示零次或一次
  • \b:单词边界,匹配单词的开始或结束
  • {3}:正好 3 个字符
  • {3,}:至少 3 个字符
  • {3,8}:3 到 8 个字符
  • |:或者
    • /apple|banana/ 表示苹果或香蕉中的任意一个
  • ():捕获和分组

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

让我们用例子来说明上述元字符。

方括号

让我们使用方括号来包含大小写。

const pattern = '[Aa]pple' // 方括号表示 A 或 a
const txt = 'Apple and banana are fruits. An old cliche says an apple a day keeps the  doctor way has been replaced by a banana a day keeps the doctor far far away. '
const matches = txt.match(pattern)

console.log(matches)  
["Apple", index: 0, input: "Apple and banana are fruits. An old cliche says an apple a day keeps the  doctor way has been replaced by a banana a day keeps the doctor far far away.", groups: undefined]
const pattern = /[Aa]pple/g // 方括号表示 A 或 a
const txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. '
const matches = txt.match(pattern)

console.log(matches)  
["Apple", "apple"]

如果我们想查找香蕉,可以按如下方式编写模式:

const pattern = /[Aa]pple|[Bb]anana/g // 方括号表示 A 或 a,B 或 b
const txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. Banana is easy to eat too.'
const matches = txt.match(pattern)

console.log(matches)  
["Apple", "banana", "apple", "banana", "Banana"]

使用方括号和或运算符,我们成功提取了 Apple、apple、Banana 和 banana。

正则表达式中的转义字符(\)

const pattern = /\d/g  // \d 是一个特殊字符,表示数字
const txt = 'This regular expression example was made in January 12,  2020.'
const matches = txt.match(pattern)

console.log(matches)  // ["1", "2", "2", "0", "2", "0"], 这不是我们想要的
const pattern = /\d+/g  // \d 是一个特殊字符,表示数字
const txt = 'This regular expression example was made in January 12,  2020.'
const matches = txt.match(pattern)

console.log(matches)  // ["12", "2020"], 这不是我们想要的

一次或多次(+)

const pattern = /\d+/g  // \d 是一个特殊字符,表示数字
const txt = 'This regular expression example was made in January 12,  2020.'
const matches = txt.match(pattern)
console.log(matches)  // ["12", "2020"], 这不是我们想要的

句点(.)

const pattern = /[a]./g  // 方括号表示 a,. 表示除换行符外的任何字符
const txt = 'Apple and banana are fruits'
const matches = txt.match(pattern)

console.log(matches)  // ["an", "an", "an", "a ", "ar"]
const pattern = /[a].+/g  // . 表示任何字符,+ 表示一次或多次
const txt = 'Apple and banana are fruits'
const matches = txt.match(pattern)

console.log(matches)  // ['and banana are fruits']

零次或多次(*)

零次或多次。模式可以不出现,或者可以出现多次。

const pattern = /[a].*/g  //. 表示任何字符,* 表示零次或多次
const txt = 'Apple and banana are fruits'
const matches = txt.match(pattern)

console.log(matches)  // ['and banana are fruits']

零次或一次(?)

零次或一次。模式可以不出现,或者可以出现一次。

const txt = 'I am not sure if there is a convention how to write the word e-mail.\
Some people write it email others may write it as Email or E-mail.'
const pattern = /[Ee]-?mail/g  // ? 表示可选
matches = txt.match(pattern)

console.log(matches)  // ["e-mail", "email", "Email", "E-mail"]

正则表达式中的量词

我们可以使用大括号指定我们在文本中查找的子字符串的长度。让我们看看如何使用 RegExp 量词。假设我们对长度为 4 个字符的子字符串感兴趣。

const txt = 'This regular expression example was made in December 6,  2019.'
const pattern = /\b\w{4}\b/g  // 精确匹配四个字符的单词
const matches = txt.match(pattern)
console.log(matches)  //['This', 'made', '2019']
const txt = 'This regular expression example was made in December 6,  2019.'
const pattern = /\b[a-zA-Z]{4}\b/g  // 精确匹配四个字符的单词,不包括数字
const matches = txt.match(pattern)
console.log(matches)  //['This', 'made']
const txt = 'This regular expression example was made in December 6,  2019.'
const pattern = /\d{4}/g  // 数字,且精确为四位
const matches = txt.match(pattern)
console.log(matches)  // ['2019']
const txt = 'This regular expression example was made in December 6,  2019.'
const pattern = /\d{1,4}/g   // 1 到 4 位
const matches = txt.match(pattern)
console.log(matches)  // ['6', '2019']

插入符号 ^

  • 以…开头
const txt = 'This regular expression example was made in December 6,  2019.'
const pattern = /^This/ // ^ 表示以…开头
const matches = txt.match(pattern)
console.log(matches)  // ['This']
  • 否定
const txt = 'This regular expression example was made in December 6,  2019.'
const pattern = /[^A-Za-z,. ]+/g  // [^] 表示否定,不是 A-Z,不是 a-z,不是空格,不是逗号,不是句号
const matches = txt.match(pattern)
console.log(matches)  // ["6", "2019"]

精确匹配

它应该以 ^ 开头,并以 $ 结尾。

let pattern = /^[A-Z][a-z]{3,12}$/;
let name = 'Asabeneh';
let result = pattern.test(name)

console.log(result) // true

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

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

相关文章

髓质脊髓三叉神经核文献阅读笔记

文献阅读 1.RNA-seq 对于大量RNA测序,收集第30天的类器官。使用FastPure细胞/组织总RNA分离试剂盒根据制造商的方案提取总RNA。采用Nanodrop 2000分光光度计测定RNA浓度和纯度。使用Agilent 2100生物分析仪和2100 RNA纳米6000检测试剂盒评估RNA样品的完整性。简单…

自动驾驶系列—从IMU到惯性定位算法:自动驾驶精准定位的幕后科技

🌟🌟 欢迎来到我的技术小筑,一个专为技术探索者打造的交流空间。在这里,我们不仅分享代码的智慧,还探讨技术的深度与广度。无论您是资深开发者还是技术新手,这里都有一片属于您的天空。让我们在知识的海洋中…

使用Git生成SSH密钥教程(附Git常用命令)

一、为什么使用SSH? 使用 Git 的 SSH(安全外壳协议)主要有以下几个原因:1. 安全性:SSH 是一种加密的网络协议,用于在网络中安全地运行网络服务。使用 SSH,所有传输的数据都会被加密&#xff0c…

FreeRTOS——系统配置文件FreeRTOSConfig.h详解

FreeRTOSConfig.h配置文件作用:对FreeRTOS进行功能配置和裁剪,以及API函数得使能。 FreeRTOSConfig.h 是一个用户级别的配置文件,不属于内核文件。每个用户可以有不同的FreeRTOSConfig.h,从而实现不同的功能配置。 对于FreeRTOS配…

C++ static静态

个人主页:Jason_from_China-CSDN博客 所属栏目:C系统性学习_Jason_from_China的博客-CSDN博客 所属栏目:C知识点的补充_Jason_from_China的博客-CSDN博客 概念概述 用 static 修饰的成员变量,称之为静态成员变量,静态成…

车辆重识别(2021NIPS无分类器扩散指南)论文阅读2024/10/08

什么叫做有条件和无条件的扩散模型? FID是什么? IS是什么? λ是给出的参数,就像去噪扩散模型中每个时间步的β一样,每一时间步的λ都会给出。对于是否有条件信息c的概率 我的意思是在每一个训练轮次中&#xf…

一个适用于 ASP.NET Core 的轻量级插件框架

前言 今天大姚给大家分享一个适用于 ASP.NET Core 的轻量级插件框架,简单配置,开箱即用:PluginCore。 项目概述 PluginCore 是一个基于 ASP.NET Core 的轻量级插件框架,旨在简化插件的集成与管理。通过最少的配置,开…

wps文本框文字居中对齐

直接点对齐里的水平居中,垂直居中是将文本框水平垂直居中,文字不会居中 将文本框里的文字居中: 垂直居中: 水平居中:

基于SpringBoot的校园健康信息管理系统

第1章 绪论 1.1背景及意义 随着社会的快速发展,计算机的影响是全面且深入的。人们生活水平的不断提高,日常生活中人们对医院管理方面的要求也在不断提高,由于老龄化人数更是不断增加,使得师生健康信息管理系统的开发成为必需而且紧…

前端反接保护:实用方案解析与探讨

前端反接保护通常采用肖特基二极管方案或PMOS/NMOS方案,本文另外介绍一种理想二极管方案。 1、肖特基二极管方案 由于肖特基二极管具有正向导通电压,只能用于小电流场合,甚至于直接使用普通的整流二极管。比如1A电流,设D1的正向…

笔记整理—linux进程部分(9)互斥锁

互斥锁也叫互斥量,可以看作一种特殊的信号量。信号量可以>0,大家可以排队使用信号量,互斥锁只有0、1,主要实现关键段保护,只能在某一时间给某一任务去调用这段资源,这段内容用之前上锁,用完时…

Spring一共有几种注入方式?

目录 一、Spring Ioc 什么是 IOC? 依赖倒置原则 为什么叫控制反转? 两种实现方式 依赖注入DI Spring有哪些注入方式? 1. 构造方法注入 2. Setter方法注入 3. 字段/属性注入 4. 方法注入 5. 接口注入 6. 注解注入 二、Spring Ao…

gaussdb hccdp认证模拟题(多选)

1.以下哪些方式可以查询数据库信息? (1 分) A. \l B. \db C. select * from pg_database; D. select * from gs_database; --AC 2.以下哪些权限是开启三权分立后系统管理员不再具备的权限? (1 分) A. 用户管理权限 B. 表空间管理权限 C. …

通信工程学习:什么是三网融合

三网融合 三网融合,又称“三网合一”,是指电信网、广播电视网、互联网在高层业务应用上的深度融合。这一概念在近年来随着信息技术的快速发展而逐渐受到重视,并成为推动信息化社会建设的重要力量。以下是对三网融合的详细解释: 一…

20.数据结构与算法-树和二叉树/满二叉树/完全二叉树/二叉树的性质/二叉树的存储结构

树的定义 树的其它表示方法 树的基本术语 树结构和线性结构的比较 二叉树的定义 二叉树案例引入 二叉树的抽象数据类型定义 二叉树的性质 两种特殊形式的二叉树 满二叉树 完全二叉树 完全二叉树的性质 二叉树的存储结构 二叉树的顺序存储 二叉树的链式存储结构 二叉链表 三叉链…

GISBox工具:轻松实现倾斜摄影数据从OSGB到3D Tiles的转变

在现代地理信息系统(GIS)和三维可视化领域,倾斜摄影数据(OSGB格式)和3D Tiles格式是两种广泛应用的数据格式。然而,将OSGB数据转换为3D Tiles格式以便在Cesium等平台上加载和展示,一直是许多开发…

[控制理论]—差分变换法与双线性变换法的基本原理和代码实现

差分变换法与双线性变换法的基本原理和代码实现 1.差分变换法 差分变换法就是把微分方程中的导数用有限差分来近似等效,得到一个与原微分方程逼近的差分方程。 差分变换法包括后向差分与前向差分。 1.1 后向差分法 差分变换如下: d e ( t ) d t e…

Stable Diffusion绘画 | 签名、字体、Logo设计

第1步,使用 PS(小白推荐使用 可画)准备一个 512*768 的签名、字体、Logo图片: 第2步,来到模型网站,搜索🔍关键词“电商”,找到一款喜欢的 LoRA: 第3步,选择一…

什么是fastText

1. 什么是fastText 英语单词通常有其内部结构和形成⽅式。例如,我们可以从“dog”“dogs”和“dogcatcher”的字⾯上推测它们的关系。这些词都有同⼀个词根“dog”,但使⽤不同的后缀来改变词的含义。而且,这个关联可以推⼴⾄其他词汇。 在wor…

初学者如何快速入门人工智能

一、引言 人工智能(Artificial Intelligence,简称AI),作为当今科技领域极具前景与影响力的方向之一,吸引着众多人士投身其中。无论是对科技充满好奇的学生,还是意图拓展职业发展路径的职场人士&#xff0c…