dotAll 模式
正則表達式中,(.)可以匹配任意字符,但是4個字節的 utf16 和\n \r 換行、回車終止符不能用(.)匹配
console.log(/foo.bar/.test('foo\nbar')); // false
console.log(/foo.bar/.test('fooabar')); // true
// 使用 dotAll模式匹配
console.log(/foo.bar/s.test('foo\nbar')); // true
驗證是否開啓dotAll 模式
const re = /foo.bar/s
// 判斷是否啓用dotAll模式
console.log(re.dotAll) // true
flags 方法,判斷正則表達式使用了哪些修飾符
const re = /foo.bar/sgiu
console.log(re.flags) // gisu
正則表達式的 match()方法及返回說明
console.log('2019-06-07'.match(/(\d{4})-(\d{2})-(\d{2})/))
// ["2019-06-07", "2019", "06", "07", index: 0, input: "2019-06-07", groups: undefined]
// [完整匹配,第一個分組,第二個分組,第三個分組,正則從字符串的第幾個字符開始匹配到的,完整的輸入字符串,分組]
const t = '2019-06-07'.match(/(\d{4})-(\d{2})-(\d{2})/)
console.log(t[1]) // 2019
console.log(t[2]) // 06
console.log(t[3]) // 07
命名分組捕獲
用 ?<分組name> 給分組命名
const t = '2019-06-07'.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/)
console.log(t)
分組命名後,groups返回值發生了變化
這樣一來就可以通過命名的分組捕獲來對匹配數據進行讀取
const t = '2019-06-07'.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/)
console.log(t.groups.year) // 2019
console.log(t.groups.month) // 06
console.log(t.groups.day) // 07
後行斷言 (?<) 先行斷言(?)
結合先行斷言和後行斷言模式一起使用:= 等於 !不等於 \1 捕獲匹配
// 先行斷言 模式:匹配到hello後開始匹配後邊的 空格和world,從左到右匹配
let test = 'hello world'
console.log(test.match(/hello(?=\sworld)/));
// ["hello", index: 0, input: "hello world", groups: undefined]
// 後行斷言 模式:判斷 world 前邊是 hello
// ?< 採用後行斷言
console.log(test.match(/(?<=hello\s)world/))
// ["world", index: 6, input: "hello world", groups: undefined]
console.log(test.match(/(?<!hello\s)world/)) // null
思考:
1、請把‘$foo %foo foo’ 字符串中前邊是$ 符號的foo 替換成bar.
2、請提取 '$1 is worth about ¥123' 字符中的美元數是多少。