当前位置: 首页 > news >正文

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

正则表达式

正则表达式(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

相关文章:

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

正则表达式 正则表达式(Regular Expression)或 RegExp 是一种小型编程语言,有助于在数据中查找模式。RegExp 可以用来检查某种模式是否存在于不同的数据类型中。在 JavaScript 中使用 RegExp,可以使用 RegExp 构造函数&#xff0…...

使用Selenium自动化测试定位iframe以及修改img标签的display属性值

在使用 Selenium 进行自动化测试时,处理 iframe 是一个常见问题。当页面中出现 iframe 时,需要先切换到该 iframe 内部,才能正常定位和操作其中的元素。以下是处理 iframe 的步骤和示例代码: 步骤 切换到 iframe:使用…...

DAY13

面试遇到的新知识点 char str[10],只有10个字符的空间,但是只能存储9个字符,最后一个字符用来存储终止符\0 strlen只会计算\n,不会计算\0 值传递: void test2(char * str) {str "hello\n"; }int main() {char * str;test2(str);…...

WPF 自定义用户控件(Content根据加减按钮改变值)

前端代码&#xff1a; <UserControl.Resources><Style x:Key"Num_Button_Style" TargetType"Button"><Setter Property"MinWidth" Value"30" /><Setter Property"Height" Value"35" />&l…...

CPU、GPU、显卡

CPU VS GPUCPU&#xff08;Central Processing Unit&#xff09;&#xff0c;中央处理器GPU&#xff08;Graphics Processing Unit&#xff09;&#xff0c;图形处理单元GPU 的技术演变CUDA&#xff08;Compute Unified Device Architecture&#xff09; 显卡&#xff08;Video…...

深入理解 Django 自定义用户模型

1. 引言 Django 作为一个强大的 Web 框架&#xff0c;内置了用户认证系统。然而&#xff0c;实际项目中我们通常需要扩展用户模型&#xff0c;以满足不同的业务需求。Django 提供了继承 AbstractUser 的方式&#xff0c;让我们能够轻松地定制用户模型。本文将通过一个自定义用…...

顺序表和链表的区别

顺序表和链表的区别 不同点顺序表链表&#xff08;带头双向循环&#xff09;存储空间物理上一定连续逻辑上连续物理上不一定连续随机访问&#xff08;用下标随机访问&#xff09;支持&#xff1a;O(1)不支持&#xff1a;O(N)任意位置插入或者删除元素可能需要搬移元素&#xf…...

系分-数据库总结

历年试题2024年05月试题 BCN范式&#xff0c;模式分解&#xff0c;触发器类型2023年05月试题 NoSQL基本特点&#xff0c;NoSQL对比&#xff0c;混合数据库2022年05月试题4 两段锁&#xff0c;事务并发&#xff0c;数据一致&#xff0c;本地事务发布20…...

new Date()解析

JavaScript 中的 new Date() 构造函数用于创建一个表示日期和时间的对象。Date 对象使得你可以以多种方式获取、设置和格式化日期和时间。让我们深入解析一下 new Date() 及其用法。 创建 Date 对象 可以通过多种方式创建 Date 对象&#xff1a; 不带参数&#xff1a; let no…...

df 的各种用法 以及与du 的区别

df的用法 在 Linux 中&#xff0c;“df”&#xff08;disk free&#xff09;是一个用于显示磁盘空间使用情况的命令。 一、主要功能 它可以列出文件系统的磁盘空间使用情况&#xff0c;包括磁盘总容量、已使用空间、可用空间以及使用率等信息。 二、常见用法及参数 基本用法&a…...

2024年下半年软考准考证什么时候打印?

2024年下半年软考准考证打印入口网址如下&#xff1a; https://bm.ruankao.org.cn/sign/welcome 广东的同学特别注意&#xff1a;准考证打印截止时间是11月8号&#xff0c;也就是考试前一天。一定要提前打印准考证&#xff0c;考试当天是无法打印的。 2024年下半年软考准考证…...

企业安全运行与维护(Enterprise Security Operation and Maintenance)

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:Linux运维老纪的首页…...

每日“亿“题 东方博宜OJ 1424-自然数的分解

原题链接&#xff1a;1424 - 自然数的分解-东方博宜OJ 题目描述 给定自然数 n &#xff0c;将其拆分成若干自然数的和。输出所有解&#xff0c;每组解中数字按从小到大排列。相同数字的不同排列算一组解。 如&#xff0c;读入整数 3 &#xff0c;分解方案如下&#xff1a; …...

初识Linux · 文件(1)

目录 前言&#xff1a; 回顾语言层面的文件 理解文件的预备知识 文件和磁盘 使用和认识系统调用函数 前言&#xff1a; 本文以及下篇文章&#xff0c;揭露的都是Linux中文件的奥秘&#xff0c;对于文件来说&#xff0c;初学Linux第一节课接触的就是文件&#xff0c;对于C…...

【MYSQL】mysql约束---自增长约束(auto_increment)

1、概念 在Mysql中&#xff0c;当主键为自增长后&#xff0c;这个主键的值就不再需要用户输入数据了&#xff0c;而由数据库系统根据定义自动赋值。每增加一条记录&#xff0c;主键会自动以相同的步长进行增长。 注意&#xff1a;自增长约束通常与主键放在一起使用。 通过给…...

基于STM32设计的智能学习台灯(华为云IOT)(238)

文章目录 一、前言1.1 项目介绍【1】开发背景【2】项目实现的功能【3】项目硬件模块组成【4】ESP8266工作模式配置1.2 设计思路【1】整体设计思路【2】整体构架【3】上位机开发思路1.3 项目开发背景【1】选题的意义【2】可行性分析【3】参考文献【4】摘要1.4 开发工具的选择【1…...

网络层协议 --- IP

序言 在这篇文章中我们将介绍 IP协议&#xff0c;经过这篇文章的学习&#xff0c;我们就会了解运营商到底是如何为我们提供服务的以及平时我们所说的内网&#xff0c;公网到底又是什么&#xff0c;区别是什么&#xff1f; IP 地址的基本概念 1. IP 地址的定义 每一个设备接入…...

Java虚拟机(JVM)介绍

**Java虚拟机&#xff08;JVM&#xff09;**是Java平台的核心组件&#xff0c;它提供了一个运行时环境&#xff0c;使得Java程序可以在不同的操作系统和硬件平台上运行而无需修改。 JVM的架构 JVM主要由以下几个部分组成&#xff1a; 类加载器&#xff08;Class Loader&#xf…...

1000题-计算机网络系统概述

术语定义与其他术语的关系SDU&#xff08;服务数据单元&#xff09;相邻层间交换的数据单元&#xff0c;是服务原语的表现形式。在OSI模型中&#xff0c;SDU是某一层待传送和处理的数据单元&#xff0c;即该层接口数据的总和。 - SDU是某一层的数据集&#xff0c;准备传递给下一…...

Authentication Lab | IP Based Auth Bypass

关注这个靶场的其它相关笔记&#xff1a;Authentication Lab —— 靶场笔记合集-CSDN博客 0x01&#xff1a;IP Based Auth Bypass 前情提要 有些开发人员为了图方便&#xff0c;会给站点设置一个 IP 白名单&#xff0c;如果访问站点的用户的 IP 在白名单内&#xff0c;则允许访…...

接口测试中缓存处理策略

在接口测试中&#xff0c;缓存处理策略是一个关键环节&#xff0c;直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性&#xff0c;避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明&#xff1a; 一、缓存处理的核…...

微软PowerBI考试 PL300-选择 Power BI 模型框架【附练习数据】

微软PowerBI考试 PL300-选择 Power BI 模型框架 20 多年来&#xff0c;Microsoft 持续对企业商业智能 (BI) 进行大量投资。 Azure Analysis Services (AAS) 和 SQL Server Analysis Services (SSAS) 基于无数企业使用的成熟的 BI 数据建模技术。 同样的技术也是 Power BI 数据…...

渲染学进阶内容——模型

最近在写模组的时候发现渲染器里面离不开模型的定义,在渲染的第二篇文章中简单的讲解了一下关于模型部分的内容,其实不管是方块还是方块实体,都离不开模型的内容 🧱 一、CubeListBuilder 功能解析 CubeListBuilder 是 Minecraft Java 版模型系统的核心构建器,用于动态创…...

论文浅尝 | 基于判别指令微调生成式大语言模型的知识图谱补全方法(ISWC2024)

笔记整理&#xff1a;刘治强&#xff0c;浙江大学硕士生&#xff0c;研究方向为知识图谱表示学习&#xff0c;大语言模型 论文链接&#xff1a;http://arxiv.org/abs/2407.16127 发表会议&#xff1a;ISWC 2024 1. 动机 传统的知识图谱补全&#xff08;KGC&#xff09;模型通过…...

Spring AI 入门:Java 开发者的生成式 AI 实践之路

一、Spring AI 简介 在人工智能技术快速迭代的今天&#xff0c;Spring AI 作为 Spring 生态系统的新生力量&#xff0c;正在成为 Java 开发者拥抱生成式 AI 的最佳选择。该框架通过模块化设计实现了与主流 AI 服务&#xff08;如 OpenAI、Anthropic&#xff09;的无缝对接&…...

C++ 求圆面积的程序(Program to find area of a circle)

给定半径r&#xff0c;求圆的面积。圆的面积应精确到小数点后5位。 例子&#xff1a; 输入&#xff1a;r 5 输出&#xff1a;78.53982 解释&#xff1a;由于面积 PI * r * r 3.14159265358979323846 * 5 * 5 78.53982&#xff0c;因为我们只保留小数点后 5 位数字。 输…...

学习STC51单片机32(芯片为STC89C52RCRC)OLED显示屏2

每日一言 今天的每一份坚持&#xff0c;都是在为未来积攒底气。 案例&#xff1a;OLED显示一个A 这边观察到一个点&#xff0c;怎么雪花了就是都是乱七八糟的占满了屏幕。。 解释 &#xff1a; 如果代码里信号切换太快&#xff08;比如 SDA 刚变&#xff0c;SCL 立刻变&#…...

sipsak:SIP瑞士军刀!全参数详细教程!Kali Linux教程!

简介 sipsak 是一个面向会话初始协议 (SIP) 应用程序开发人员和管理员的小型命令行工具。它可以用于对 SIP 应用程序和设备进行一些简单的测试。 sipsak 是一款 SIP 压力和诊断实用程序。它通过 sip-uri 向服务器发送 SIP 请求&#xff0c;并检查收到的响应。它以以下模式之一…...

CVE-2020-17519源码分析与漏洞复现(Flink 任意文件读取)

漏洞概览 漏洞名称&#xff1a;Apache Flink REST API 任意文件读取漏洞CVE编号&#xff1a;CVE-2020-17519CVSS评分&#xff1a;7.5影响版本&#xff1a;Apache Flink 1.11.0、1.11.1、1.11.2修复版本&#xff1a;≥ 1.11.3 或 ≥ 1.12.0漏洞类型&#xff1a;路径遍历&#x…...

CRMEB 中 PHP 短信扩展开发:涵盖一号通、阿里云、腾讯云、创蓝

目前已有一号通短信、阿里云短信、腾讯云短信扩展 扩展入口文件 文件目录 crmeb\services\sms\Sms.php 默认驱动类型为&#xff1a;一号通 namespace crmeb\services\sms;use crmeb\basic\BaseManager; use crmeb\services\AccessTokenServeService; use crmeb\services\sms\…...