方法之一:开启 Vim 的 very magic option
| Level of magic | Prefix | Description |
|---|---|---|
| Very magic | \v |
All possible metacharacters are available without escaping them. |
| Magic | \m |
Only some metacharacters are available without escaping them. The others need to be escaped. |
| Nomagic | \M |
Only some literal characters are available without escaping them. The others need to be escaped. |
| Very nomagic | \V |
All possible literal characters are available without escaping them. |
详见「Diving Deeper in Vim Regular Expressions」。
在正则表达式前加上 \v ,这样就不用带上各种丑陋的转义符 \ 了。当然,代价是丑,且只是接近正宗正则,但不保真。
方法之二:借助外部命令,调用真 perl
:%!perl -pe "s/<regexp>/<replacement>g"
代价是「怎么即时搜索呢?」。正则表达式一般都要调试好几次,才能写出准确的正则。调用 perl 的方式显然不适合调试。
方法之三::perldo command
如果你的 Vim 在编译时打开了 +perl,那么可以用 :perldo 命令实现正则替换。缺点同样是不支持搜索,不适合调试。
:perldo s/\A[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}\z/platypus/g
# replace all UUIDs with the word 'platypus'
详见「Perl Compatible Regular Expressions in vim」。
方法之四:上插件
找到一个 2023 年就不更新的 othree/eregex.vim,缺点是不支持即时搜索。本来有人提交了修改,但不知道为什么主开发不采纳。∴这人 fork 了一个带增量搜索的版本 ZSaberLv0/eregex.vim 。