**摘要:**正则表达式是程序员的必备技能,想不想多学几招呢?
本文用Javascript的exec方法来测试正则表达式。
例如,正则表达式**/F.*g/会匹配“以F开头,以g结尾的字符串”,因此可以匹配"Hello, Fundebug!"中的Fundebug**,exec方法会返回一个数组,其第一个元素为所匹配的子字符串。
/F.*g/.exec("Hello, Fundebug!")[0]
// 'Fundebug'
非贪婪匹配
默认情况下,正则表达式的量词***、+、?、{},都是进行贪婪匹配,即匹配尽可能多的字符**。
例如,正则表达式**/.+s.+?s[a-z]+(?=.com)d+(?!.)^forever.+forever.+/m**:
/^forever.+/m.exec("May God bless and keep you always,nmay your wishes all come true,nmay you always do for othersnand let others do for you.nmay you build a ladder to the starsnand 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号元素。
参考-
MDN:正则表达式



