解決 Sublime Text 正則表示式搜尋,遇到的「Invalid lookbehind assertion」錯誤

Sublime Text 正則表示式 (regular expression) 搜尋時,視窗底部顯示「Invalid lookbehind assertion encountered in the regular expression. In regular expression (?<=95|98|NT|2000)Windows」錯誤訊息。

狀況
參考維基百科正規表示式的說明:
反向肯定預查,與正向肯定預查類似,只是方向相反。例如,「(?<=95|98|NT|2000)Windows」能匹配「2000Windows」中的「Windows」,但不能匹配「3.1Windows」中的「Windows」。
但是搜尋   (?<=95|98|NT|2000)Windows 反而遇到「Invalid lookbehind assertion 」錯誤。

原因與解決方法

非官方 Sublime text 說明手冊提到正則表示式是使用 Boost 函式庫的語法。而 Boost 語法在反向肯定預查部分, pattern 必須要固定長度。
(?<=pattern) consumes zero characters, only if pattern could be matched against the characters preceding the current position (pattern must be of fixed length).

因此原本 (?<=95|98|NT|2000)Windows 中的 pattern 改成固定長度 (?<=95|98|NT)Windows 就可以進行搜尋。而不同長度的 pattern 則需要獨立出來,額外一次進行搜尋 (?<=2000)Windows 。

參考資料
  1. replace - Regex in sublimetext to find specific html element - Stack Overflow 

相關資料
  1. Lookahead and Lookbehind Tutorial—Tips &Tricks 
  2. 正則表示法快速查表

留言

  1. 很有幫助。但這個限制實在是使得前向肯定變得很不好用。

    回覆刪除
    回覆
    1. 有一好沒兩好 實際使用只好換別樣工具

      刪除

張貼留言