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

ES6 正则的扩展(十九)

1. 正则表达式字面量改进

特性:在 ES6 中,正则表达式字面量允许在字符串中使用斜杠(/)作为分隔符。
用法:简化正则表达式的书写。

const regex1 = /foo/;
const regex2 = /foo/g; // 全局搜索

2. u 修饰符(Unicode)

特性:u 修饰符允许正则表达式正确处理 Unicode 字符。
用法:确保正则表达式在处理多字节字符时表现正确。

const regex = /foo/u;
console.log(regex.test("foö")); // 输出:false

3. y 修饰符(Sticky)

特性:y 修饰符使正则表达式在搜索时“粘”在每个匹配的开始位置。
用法:进行连续的匹配搜索。

const text = "abcabc";
const regex = /abc/y;let match;
while ((match = regex.exec(text)) !== null) {console.log(`Found ${match[0]} at index ${match.index}`);
}
// 输出:
// Found abc at index 0
// Found abc at index 3

4. 新增的正则表达式方法

特性:String.prototype.match(), String.prototype.replace(), String.prototype.search(), 和 String.prototype.split() 现在可以接受正则表达式字面量。
用法:直接使用正则表达式进行字符串处理。

const text = "Hello World";
const regex = /Hello/;console.log(text.match(regex)); // 输出:["Hello"]
console.log(text.replace(regex, "Hi")); // 输出:"Hi World"
console.log(text.search(regex)); // 输出:0
console.log(text.split(regex)); // 输出:["", " World"]

5. flags 属性

特性:正则表达式对象现在有一个 flags 属性,返回正则表达式的修饰符。
用法:获取正则表达式使用的修饰符。

const regex = /foo/g;
console.log(regex.flags); // 输出:"g"

6. dotAll 模式(点字符匹配所有)

特性:当设置了 s 修饰符(dotAll)时,点字符(.)可以匹配包括换行符在内的任何字符。
用法:进行多行匹配。

const text = "foo\nbar";
const regex = /bar/s; // 使用 dotAll 模式console.log(regex.test(text)); // 输出:true

7. hasIndices 属性

特性:hasIndices 属性用于指示正则表达式是否捕获分组。
用法:检查正则表达式是否包含捕获组。

const regex1 = /foo/;
const regex2 = /foo(bar)/;console.log(regex1.hasIndices); // 输出:false
console.log(regex2.hasIndices); // 输出:true

8. Symbol.match, Symbol.replace, Symbol.search, Symbol.split

特性:这些 Symbol 属性允许使用正则表达式进行字符串匹配、替换、搜索和分割。
用法:提供一种更灵活的方式来处理字符串。

const text = "Hello World";
const regex = /world/i;console.log(text[Symbol.match](regex)); // 输出:["World"]
console.log(text[Symbol.replace](regex, "there")); // 输出:"Hello there"
console.log(text[Symbol.search](regex)); // 输出:4
console.log(text[Symbol.split](regex)); // 输出:["Hello ", ""]
http://www.lryc.cn/news/403475.html

相关文章:

  • <数据集>钢铁缺陷检测数据集<目标检测>
  • Kafka系列之:Kafka存储数据相关重要参数理解
  • Template execution failed: ReferenceError: name is not defined
  • CVE-2024-24549 Apache Tomcat - Denial of Service
  • Linux下如何安装配置Graylog日志管理工具
  • 「MQTT over QUIC」与「MQTT over TCP」与 「TCP 」通信测试报告
  • 获取磁盘剩余容量-----c++
  • AI算法24-决策树C4.5算法
  • 【云原生】Prometheus整合Alertmanager告警规则使用详解
  • C++ :友元类
  • 【整理了一些关于使用swoole使用的解决方案】
  • python selenium4 EdgeDriver动态页面爬取
  • 【一次记一句:SQL】从 information_schema.TABLES中查询数据库表中记录数据量
  • NXP i.MX8系列平台开发讲解 - 3.19 Linux TTY子系统(二)
  • FPGA资源容量
  • Zabbix介绍和架构
  • 打造智慧图书馆:AI视频技术助力图书馆安全与秩序管理
  • Go的数据结构与实现【LinkedList】
  • Ubuntu22.04安装CUDA+CUDNN+Conda+PyTorch
  • 当“广撒网”遇上“精准定点”的鱼叉式网络钓鱼
  • svn ldap认证临时切换到本地认证
  • 极狐GitLab如何配置使用独立数据库?
  • TCP状态转换详解
  • SimMIM:一个类BERT的计算机视觉的预训练框架
  • 数据精度丢失
  • Element UI DatePicker选择日期范围区间默认显示前一个月和本月
  • C++:聚合类、嵌套类、局部类、union类详细介绍与分析
  • MKS流量计软件MFC通讯驱动使用于C和P系列MFC控制USB接口W10系统
  • C++:左值/右值引用、移动语义/std::move、万能引用/完美转发std::forward 详解
  • 蜂窝物联云平台:一站式服务,智能生活从此开始!