正则表达式梳理

文章目录


正则表达式

正则表达式是一种用来描述字符串规则的表达式。 用于判断字符串是否符合该规则

在js中这样使用

javascript 复制代码
const reg = /abc/;
reg.test('字符串')
//用于判断字符串是否符合定义的reg规则

以下总结js中一些常用的规则

元字符

  1. [abc]匹配 a 或 b 或 c
  2. 当需要的元素够多时,可以使用区间简写区间[a-z0-9]

修饰符

加在末尾的修饰符

  1. g全局匹配
javascript 复制代码
const str = "cat bat fat";

// 1. 没有全局标志 g
const reg1 = /at/;
console.log(str.match(reg1)); 
// 结果:["at"]  (只找到第一个就停止)

// 2. 有全局标志 g
const reg2 = /at/g;
console.log(str.match(reg2)); 
// 结果:["at", "at", "at"]  找到所有

利用其进行替换

javascript 复制代码
// 替换
    const willre ='我777515474我'
    const aim =willre.replace(/我/i,'你')
    const aim1 =willre.replace(/我/g,'你')
    console.log(aim);
    console.log(aim1);//全局替换
  1. i忽略大小写

量词

  1. {n} 恰好 n 次
  2. {n,} 至少 n 次
  3. {n,m} n 到 m 次

?等价于 {0,1}
*等价于{0,}
+等价于 {1,}

位置锚点

  1. ^ 字符串开始
  2. $ 字符串结尾

当规则为/^a$/此时则只有字符a匹配该规则

此外还有|选择表达式
/规则a|规则b/,满足其中任一即匹配

这是一些综合以上规则的判断

javascript 复制代码
 const reg2=/^哈/
    console.log(reg2.test('哈哈'))

    // $以..结尾
    const reg3=/哈$/
    console.log(reg3.test('哈哈'))
    //俩个都有是精确匹配 只有此一种为true
    const reg4=/^哈$/
    console.log(reg3.test('哈'))
    // 元字符量词
    // 重复次数
    console.log(/[a-zA-Z0-9]{4,10}/.test('asd'))

一些常用的正则表达式

  1. 手机号
    /^1[3-9]\d{9}$/
  2. 邮箱
    /^[\w\.-]+@[\w\.-]+\.\w+$/
  3. 汉字
    ^[\u4e00-\u9fa5]{0,}$
  4. 邮箱
    ^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
相关推荐
linuxxx1101 小时前
正则匹配应用小案例
数据库·正则表达式
威风的虫4 小时前
常用的正则表达式
正则表达式
Lv11770085 小时前
Visual Studio中的正则表达式
ide·笔记·正则表达式·c#·visual studio
故事不长丨13 小时前
C#正则表达式完全攻略:从基础到实战的全场景应用指南
开发语言·正则表达式·c#·regex
YxVoyager1 天前
Qt C++ :QRegularExpression 正则表达式使用详解
c++·qt·正则表达式
laocooon5238578862 天前
正则表达式的全面介绍
正则表达式
ben9518chen2 天前
正则表达式
正则表达式
半路_出家ren2 天前
17.python爬虫基础,基于正则表达式的爬虫,基于BeautifulSoup的爬虫
网络·爬虫·python·网络协议·正则表达式·网络爬虫·beautifulsoup
Good_Starry3 天前
Java——正则表达式
java·开发语言·正则表达式
@zulnger3 天前
正则表达式
数据库·正则表达式