当前位置: 首页 > 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;则允许访…...

linux中的火墙优化策略

1.火墙介绍 1. netfilter 2. iptables 3. iptables | firewalld 2.火墙管理工具切换 在rocky9 中默认使用的是 firewalld firewalld -----> iptables dnf install iptables - services - y systemctl stop firewalld systemctl disable firewalld systemctl mask fi…...

GO网络编程(三):海量用户通信系统1:登录功能初步

一、准备工作 需求分析 1)用户注册 2)用户登录 3)显示在线用户列表 4)群聊(广播) 5)点对点聊天 6)离线留言 主界面 首先&#xff0c;在项目根目录下初始化mod&#xff0c;然后按照如下结构设计目录&#xff1a; 海量用户通信系统/ ├── go.mod ├── client/ │ ├──…...

Windows安全加固详解

一、补丁管理 使用适当的命令或工具&#xff0c;检查系统中是否有未安装的更新补丁。 Systeminfo 尝试手动安装一个系统更新补丁。 • 下载适当的补丁文件。 • 打开命令提示符或PowerShell&#xff0c;并运行 wusa.exe <patch_file_name>.msu。 二、账号管…...

JavaScript函数基础(通俗易懂篇)

10.函数 10.1 函数的基础知识 为什么会有函数&#xff1f; 在写代码的时候&#xff0c;有一些常用的代码需要书写很多次&#xff0c;如果直接复制粘贴的话&#xff0c;会造成大量的代码冗余&#xff1b; 函数可以封装一段重复的javascript代码&#xff0c;它只需要声明一次&a…...

云RDS MySQL迁移至本地MySQL

本地准备工作 1.安装:percona-xtrabackup 上传percona-xtrabackup-2.3.9-Linux-x86_64.tar.gz包到/usr/local tar -zxvf percona-xtrabackup-2.3.9-Linux-x86_64.tar.gz mv percona-xtrabackup-2.3.9-Linux-x86_64 percona-xtrabackup 2.创建数据目录 cd /data/ mkdir rds-mys…...

【C++ 11】nullptr 空指针

文章目录 【 0. 问题背景 】0.1 野指针和悬空指针0.2 传统空指针 NULL0.3 传统空指针的局限性 【 1. 基本用法 】【 2. nullptr 的应用 】2.1 nullptr 解决 NULL 的遗留BUG2.2 简单实例 【 0. 问题背景 】 0.1 野指针和悬空指针 总结 野指针悬空指针产生原因指针变量未被初始…...

Flutter + Three.js (WebView)实现桌面端3d模型展示和交互

文章目录 flutter(桌面端)瓶颈一、Flutterthree.js二、Flutterthree.js 实现思路1.在Flutter 中使用webview 进行嵌套2.开启上面嵌套的页面地址2.在含有three.js 的html 中引入模型3.两个页面之间进行通信&#xff0c;如图&#xff1a; 总结 flutter(桌面端)瓶颈 Flutter 本身…...

学习日志35

拆卸线问题&#xff08;Disassembly Line Balancing Problem, DLBP&#xff09;是生产工程和运筹学中的一个特殊问题&#xff0c;它涉及到将废弃产品有效地拆解成可回收利用的部件和材料。随着环保意识的增强和资源回收技术的发展&#xff0c;DLBP逐渐成为研究的热点。这类问题…...

http cache-control

Cache-Control 是 HTTP 协议中用于控制缓存行为的重要头部字段。它定义了客户端和服务器端如何缓存资源&#xff0c;以及缓存的有效期。以下是关于 Cache-Control 的详细解释&#xff1a; 请求指令 max-age 指示客户端接受的响应最大年龄。如果缓存的响应超过这个年龄&#x…...

kubernetes 中的微服务

微服务&#xff1a;用控制器来完成集群的工作负载&#xff0c;那么应用如何暴漏出去&#xff1f;需要通过微服务暴漏出去后才能被访问 - Service是一组提供相同服务的Pod对外开放的接口。 - 借助Service&#xff0c;应用可以实现服务发现和负载均衡。 - service默认只支持…...