正则表达式小记

一、什么是正则表达式?

1.定义

正则表达式(Regular Expression)是由字符和特殊符号组成的 "模式字符串",本质是一种描述文本规则的语法,可用于匹配、查找、替换或验证字符串中指定的内容。

2.组成

普通字符(字母、数字)和特殊字符("元字符")组成

字符类

  • 量词
  • 位置词

3.小练

复制代码
#手机号验证
^1[3-9]\d{9}$

1开始,第二位是3-9的数字,匹配后9位数字

复制代码
#邮箱验证
^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$

a-zA-Z0-9_-\]匹配内容为大小写字母、数字、下划线、减号;+匹配至少一位; .表示. ### 二、拓展 下面是一个字符分割的案例 ```c if (res.code == 0 || res.code == 200) { const processedData = []; const FIELDS = [ '质量损失', '外观等级', '样品尺寸:宽', '样品尺寸:长', '样品尺寸:面积', '测试前质量', '测试后质量' ]; const checkField = (val) => { if (!val || typeof val !== 'string') return null; const reg = /([\d,.]+)\(([\d,.]+)\)/; const match = val.match(reg); if (!match) return null; const before = match[1].trim(); const inside = match[2].trim(); // 剩余内容截取 // const bracketStartIndex = val.indexOf(')') + 1; // const restValue = bracketStartIndex > 0 ? val.substring(bracketStartIndex) : ''; // 数字校验 const numCheckReg = /^[\d,.]+$/; if (!numCheckReg.test(before) || !numCheckReg.test(inside)) return null; // 数组匹配 const beforeArr = before.split(',').map(item => item.trim()); const insideArr = inside.split(',').map(item => item.trim()); if (beforeArr.length !== insideArr.length) return null; const isAllMatch = beforeArr.every((item, index) => item === insideArr[index]); return isAllMatch ? beforeArr : null; }; ``` * 推荐应用实例文章: [正则表达式应用](https://blog.csdn.net/Ed7zgeE9X/article/details/133801677?ops_request_misc=&request_id=&biz_id=102&utm_term=%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E5%B8%B8%E8%A7%81%E5%BA%94%E7%94%A8&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-0-133801677.142%5Ev102%5Epc_search_result_base4&spm=1018.2226.3001.4187)

相关推荐
XMYX-014 小时前
33 - Go 文本模板 template:从入门到原理深挖
golang·正则表达式
XMYX-018 小时前
32 - Go 正则表达式:从匹配字符串到理解 RE2 引擎
golang·正则表达式
程序员榴莲2 天前
Python 正则表达式入门:从匹配手机号到提取文本内容
python·正则表达式
红茶要加冰3 天前
七、正则表达式
linux·运维·正则表达式·shell
Pocker_Spades_A3 天前
Python快速入门专业版(五十八)——正则表达式(re):爬虫文本提取利器(从语法到实战)
爬虫·python·正则表达式
红茶要加冰4 天前
九、文本处理三剑客——sed
linux·运维·服务器·正则表达式·shell
Bug-制造者4 天前
正则表达式 vs Shell通配符:彻底分清,告别命令行踩坑
linux·正则表达式
剑神一笑6 天前
Linux top 命令深度解析:进程监控的性能优化实战
linux·运维·正则表达式
jayson.h6 天前
正则表达式:从文件名提取器件编号
开发语言·python·正则表达式
水木流年追梦6 天前
大模型入门-应用篇3-Agent智能体
开发语言·python·算法·leetcode·正则表达式