当前位置:网站首页>正则系列之量词(Quantifiers)
正则系列之量词(Quantifiers)
2022-07-01 21:50:00 【老__L】
量词表示要匹配的字符或表达式的数量。
1、x*
将前面的项“x”匹配 0 次或更多次。
let reg = /bo*/g;
let str = "A ghost booooed";
str.match(reg); // ['boooo']
str = "A bird warbled";
str.match(reg); // ['b', 'b']
str = "A goat grunted";
str.match(reg); // null
2、x+
将前一项“x”匹配 1 次或更多次,等价于{1,}
。
let reg = /bo+/g;
let str = "A ghost booooed";
str.match(reg); // ['boooo']
str = "A bird warbled";
str.match(reg); // null
str = "A goat grunted";
str.match(reg); // null
reg = /a+/g;
str = "caaaaaaandy";
str.match(reg); // ['aaaaaaa']
3、x?
将前面的项“x”匹配 0 或 1 次。
如果在任何量词*
、+
、?
或{}
之后使用?
,则使量词是非贪婪的 (匹配最小次数),而不是默认的贪婪的 (匹配最大次数)。
let reg = /bo?/g;
let str = "A ghost booooed";
str.match(reg); // ['bo']
str = "A bird warbled";
str.match(reg); // ['b', 'b']
str = "A goat grunted";
str.match(reg); // null
reg = /bo??/g;
str = "A ghost booooed";
str.match(reg); // ['b']
4、x{n}
其中“n”是一个正整数,与前一项“x”的 n 次匹配。
let reg = /a{2}/g;
let str = "candy";
str.match(reg); // null
str = "caandy";
str.match(reg); // ['aa']
str = "caaandy";
str.match(reg); // ['aa']
5、x{n,}
其中,“n”是一个正整数,与前一项“x”至少匹配“n”次。
let reg = /a{2,}/g;
let str = "caaandy";
str.match(reg); // ['aaa']
6、x{n,m}
其中n为0或正整数,m为正整数,且m > n,前一项x至少匹配n次且最多匹配m次。
let reg = /a{2,4}/g;
let str = "caaaaaaaaaaandy";
str.match(reg); // ['aaaa', 'aaaa', 'aaa']
7、x*?
x+?
x??
x{n}?
x{n,}?
x{n,m}?
默认情况下,像*
和+
这样的量词是“贪婪的”,这意味着它们试图匹配尽可能多的字符串。量词后面的字符?
使量词“非贪婪”:这意味着一旦找到匹配,它就会停止。
let reg = /a{2,4}?/g;
let str = "caaaaaaaaaaandy";
str.match(reg); // ['aa', 'aa', 'aa', 'aa', 'aa']
后记
如果你感觉文章不咋地
//(ㄒoㄒ)//
,就在评论处留言,作者继续改进;o_O???
如果你觉得该文章有一点点用处,可以给作者点个赞;\\*^o^*//
如果你想要和作者一起进步,可以微信扫描二维码,关注前端老L;~~~///(^v^)\\\~~~
谢谢各位读者们啦(^_^)∠※
!!!
边栏推荐
猜你喜欢
[jetcache] how to use jetcache
【目标跟踪】|单目标跟踪指标
SAP ui5 application development tutorial 104 - multi select support for SAP ui5 table controls and how to use code to select multiple table row items at a time
Learn MySQL from scratch - database and data table operations
详解Kubernetes网络模型
Fiori 应用通过 Adaptation Project 的增强方式分享
Dark horse programmer - software testing - stage 06 2-linux and database-01-08 Chapter 1 - description of the content of the Linux operating system stage, description of the basic format and common fo
Slope compensation
MySQL中对于索引的理解
Appium自动化测试基础 — 补充:Desired Capabilities参数介绍
随机推荐
Slope compensation
H5 model trained by keras to tflite
【图像分割】2021-SegFormer NeurIPS
447 Bili Bili noodles warp 1
LC501. 二叉搜索树中的众数
map容器
园区全光技术选型-中篇
2020-ViT ICLR
GenICam GenTL 标准 ver1.5(4)第五章 采集引擎
MySQL数据库详细学习教程
MySQL的视图练习题
Mixconv code
SAP 智能机器人流程自动化(iRPA)解决方案分享
【QT小作】封装一个简单的线程管理类
Lc669. Prune binary search tree
Favorite transaction code management tool in SAP GUI
互联网的智算架构设计
Appium自动化测试基础 — APPium安装(一)
Object memory layout
The median salary of TSMC's global employees is about 460000, and the CEO is about 8.99 million; Apple raised the price of iPhone in Japan; VIM 9.0 release | geek headlines