本文用JavaScript的exec方法來測試正則表達式。
例如,正則表達式/F.*g/會匹配“以F開頭,以g結尾的字符串”,因此可以匹配”Hello, Fundebug!”中的Fundebug,exec方法會返回一個數組,其第一個元素為所匹配的子字符串。
<table><tbody>/F.*g/.exec("Hello, Fundebug!")[0]// 'Fundebug'/<tbody>/<table>
非貪婪匹配
默認情況下,正則表達式的量詞*、+、?、{},都是進行貪婪匹配,即匹配儘可能多的字符。
例如,正則表達式/.+\s/匹配的是“以空格符結尾的字符串”,我們用它來匹配蘋果公司創始人喬布斯在斯坦福大學演講的名言“You time is limited, so don’t waste it living someone else’s life.”:
<table><tbody>/.+\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 '/<tbody>/<table>
.可以匹配任意字符,而+表示匹配1次或者多次,且是貪婪的,因此/.+\s/匹配到了最後一個空格符才結束。
當我們在量詞
例如,正則表達式/.+?\s/匹配到第一個空格符就會結束:
<table><tbody>/.+?\s/.exec("You time is limited, so don’t waste it living someone else’s life.")[0]// 'You '/<tbody>/<table>
正向肯定查找
使用正則表達式x(?=y),可以匹配’x’僅僅當’x’後面跟著’y’。這話有點繞,簡單地說,就是匹配後面是y的x,這裡的x和y都代表正則表達式。
例如,對於博客RabbitMQ入門教程的地址”https://blog.fundebug.com/2018/04/20/rabbitmq_tutorial/",如果需要匹配出域名fundebug的話,可以使用**/[a-z]+(?=\.com)/**,匹配“在.com前面的英文單詞”
<table><tbody>/[a-z]+(?=\.com)/.exec("https://blog.fundebug.com/2018/04/20/rabbitmq_tutorial/")[0]// 'fundebug'/<tbody>/<table>
正向否定查找
與正向肯定查找所對應的是正向否定查找,使用正則表達式x(?!y),可以”匹配’x’僅僅當’x’後面不跟著’y’”。
例如,小學生都知道的圓周率是3.1415926,不會的同學可以這樣記“山頂上有一座寺廟,寺廟裡面有一壺酒,還有一塊肉”。如何匹配小數點後面的數字呢?可以使用/\d+(?!\.)/,匹配”後面沒有小數點的數字”:
<table><tbody>/\d+(?!\.)/.exec("3.1415926")[0]// '1415926'/<tbody>/<table>
而使用之前提到的正向肯定查找,就可以匹配小數點前面的數字:
<table><tbody>/\d+(?=\.)/.exec("3.1415926")[0]// '3'/<tbody>/<table>
多行匹配
下面是鮑勃·迪倫的《Forever Young》歌詞:
<table><tbody>May God bless and keep you always,may your wishes all come true,may you always do for othersand let others do for you.may you build a ladder to the starsand climb on every rung,may you stay forever young,forever young, forever young,May you stay forever young./<tbody>/<table>
如何匹配以forever開頭的那句歌詞forever young, forever young呢?
這樣寫/^forever.+/是錯誤的:
<table><tbody>/^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/<tbody>/<table>
為什麼錯了?因為^匹配的整個字符串的開始,而是不是每一行的開始。
正則表達式指定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,'/<tbody>/<table>
捕獲括號
在正則表達式中使用小括號(),可以提取出字符串中的特定子串。
例如,Fundebug是在2016年雙11正式上線的,時間是”2016-11-11”,如何提取其中的年、月、日呢?如下:
<table><tbody>/(\d{4})-(\d{2})-(\d{2})/.exec("2016-11-11")// [ '2016-11-11', '2016', '11', '11', index: 0, input: '2016-11-11' ]/<tbody>/<table>
可知,3個小括號中的正則表達式分別匹配的是年月日,其結果依次為exec返回數組中的1到3號元素。