JavaScript正则表达式进阶指南

摘要:正则表达式是程序员的必备技能,想不想多学几招呢?javascript

图片描述

本文用JavaScript的exec方法来测试正则表达式。java

例如,正则表达式/F.*g/会匹配“以F开头,以g结尾的字符串”,所以能够匹配"Hello, Fundebug!"中的Fundebug,exec方法会返回一个数组,其第一个元素为所匹配的子字符串。程序员

/F.*g/.exec("Hello, Fundebug!")[0]
// 'Fundebug'

非贪婪匹配

默认状况下,正则表达式的量词*、+、?、{},都是进行贪婪匹配,即匹配尽量多的字符正则表达式

例如,正则表达式/.+s/匹配的是“以空格符结尾的字符串”,咱们用它来匹配苹果公司创始人乔布斯在斯坦福大学演讲的名言“You time is limited, so don’t waste it living someone else’s life.”:数组

/.+\s/.exec("You time is limited, so don’t waste it living someone else’s life.")[0]
// 'You time is limited, so don’t waste it living someone else’s '

.能够匹配任意字符,而+表示匹配1次或者屡次,且是贪婪的,所以/.+s/匹配到了最后一个空格符才结束。less

当咱们在量词*、+、?、{}后面紧跟着一个?,就能够实现非贪婪匹配,即匹配尽可能少的字符ide

例如,正则表达式/.+?s/匹配到第一个空格符就会结束:测试

/.+?\s/.exec("You time is limited, so don’t waste it living someone else’s life.")[0]
// 'You '

正向确定查找

使用正则表达式x(?=y),能够匹配'x'仅仅当'x'后面跟着'y'。这话有点绕,简单地说,就是匹配后面是y的x,这里的x和y都表明正则表达式。ui

例如,对于博客RabbitMQ入门教程的地址"https://blog.fundebug.com/2018/04/20/rabbitmq_tutorial/",若是须要匹配出域名fundebug的话,可使用/[a-z]+(?=.com)/,匹配“在.com前面的英文单词”spa

/[a-z]+(?=\.com)/.exec("https://blog.fundebug.com/2018/04/20/rabbitmq_tutorial/")[0]
// 'fundebug'

广告:欢迎免费试用Fundebug,为您监控线上代码的BUG,提升用户体验~

正向否认查找

与正向确定查找所对应的是正向否认查找,使用正则表达式x(?!y),能够"匹配'x'仅仅当'x'后面不跟着'y'"。

例如,小学生都知道的圆周率是3.1415926,不会的同窗能够这样记“山顶上有一座寺庙,寺庙里面有一壶酒,还有一块肉”。如何匹配小数点后面的数字呢?可使用/d+(?!\.)/,匹配"后面没有小数点的数字":

/\d+(?!\.)/.exec("3.1415926")[0]
// '1415926'

而使用以前提到的正向确定查找,就能够匹配小数点前面的数字:

/\d+(?=\.)/.exec("3.1415926")[0]
// '3'

多行匹配

下面是鲍勃·迪伦的《Forever Young》歌词:

May God bless and keep you always,
may your wishes all come true,
may you always do for others
and let others do for you.
may you build a ladder to the stars
and climb on every rung,
may you stay forever young,
forever young, forever young,
May you stay forever young.

如何匹配以forever开头的那句歌词forever young, forever young呢?

这样写/^forever.+/是错误的:

/^forever.+/.exec("May God bless and keep you always,\nmay your wishes all come true,\nmay you always do for others\nand let others do for you.\nmay you build a ladder to the stars\nand climb on every rung,\nmay you stay forever young,\nforever young, forever young,\nMay you stay forever young.")
// null

为何错了?由于^匹配的整个字符串的开始,而是否是每一行的开始。

正则表达式指定m选项,便可支持多行匹配,这时^$匹配的是每一行的开始和结束,所以正确的正则表达式是/^forever.+/m

/^forever.+/m.exec("May God bless and keep you always,\nmay your wishes all come true,\nmay you always do for others\nand let others do for you.\nmay you build a ladder to the stars\nand climb on every rung,\nmay you stay forever young,\nforever young, forever young,\nMay you stay forever young.")[0]
// 'forever young, forever young,'

捕获括号

在正则表达式中使用小括号(),能够提取出字符串中的特定子串。

例如,Fundebug是在2016年双11正式上线的,时间是"2016-11-11",如何提取其中的年、月、日呢?以下:

/(\d{4})-(\d{2})-(\d{2})/.exec("2016-11-11")
// [ '2016-11-11', '2016', '11', '11', index: 0, input: '2016-11-11' ]

可知,3个小括号中的正则表达式分别匹配的是年月日,其结果依次为exec返回数组中的1到3号元素。

参考