avatar

[JavaScript]-Regex

regex.exec

  • 參數

    • string:要搜尋的字串
  • Return

    • 如果找到匹配 → 回傳一個 Array
    • 如果沒找到匹配 → 回傳 null
  • 範例

const regex = /(\d+)-(\w+)/; const result = regex.exec("123-apple"); console.log(result); // [ // "123-apple", // 完整匹配的字串 // "123", // 第1個捕獲組 (第一個括號) // "apple", // 第2個捕獲組 (第二個括號) // index: 0, // 匹配開始的位置 // input: "123-apple", // 原始字串 // groups: undefined // 若有命名群組才會有這欄 // ]

反覆查詢 (g)

g 代表 global(全域搜尋),會讓正則表達式不只找第一個匹配,而是繼續找整個字串中所有的匹配。 配合 .exec() 可以利用 regex.lastIndex 屬性逐一遍歷結果。

const regex = /\d+/g; const str = "數字 12 和 34 還有 56"; let match; while ((match = regex.exec(str)) !== null) { console.log(`找到 ${match[0]},位置 ${match.index}`); } // 找到 12,位置 3 // 找到 34,位置 7 // 找到 56,位置 12

多行模式 (m )

m 代表 multiline(多行模式)。 在預設情況下:

  • ^ 只匹配整個字串的開頭;
  • $ 只匹配整個字串的結尾。

加上 m 後, ^$ 會匹配每一行的開頭與結尾(遇到 \n 換行時也會重置)。

const regex = /^#.+$/gm; const str = ` # Title 1 ## Title 2 ### Title 3 `; let match; while ((match = regex.exec(str)) !== null) { console.log(`匹配到: ${match[0]}`); } // 匹配到: # Title 1 // 匹配到: ## Title 2 // 匹配到: ### Title 3

常見整理

旗標名稱功能說明
gglobal全域搜尋,找出所有匹配結果
iignoreCase忽略大小寫
mmultiline^$ 匹配每一行的開頭與結尾
sdotAll. 也能匹配換行符號
uunicode正確處理 Unicode 字符(例如 emoji)
ysticky從上次匹配結束位置繼續匹配