使用 Sublime 的正则表达式 search/replace 和 \Z

Using Sublime's regex search/replace with \Z

Sublime 似乎认为 \Z 匹配文件的实际结尾,
每个 \n 导致它。

这是 Sublime 中的错误吗
(意思是,Sublime 或它正在使用的东西),
还是正确的行为
我只是对它应该如何工作感到困惑?

这里有一个简单的具体演示:

这是搜索替换:

   Find What:\Z
Replace With:y

这里有 4 个例子:

    - the original file contents
    - the actual   result
    - my  expected result

eg0 - \n 最后:0

(如我所料。)

原文:

x0
x
x
x

实际:

x0
x
x
xy

预计:

x0
x
x
xy

((
Stackexchange 格式在这里乱七八糟,
并开始忽略 #.* 行,
而且我不知道如何解决它,
pre 标签内容仍然没问题。
编辑:
post 中的实际格式本身有效,
但是格式在 post(显示在编辑框下方)的 preview 中乱七八糟。
))

eg1 - \n 最后:1

原文:

x1
x
x
x

实际:

x1
x
x
xy
y

预计:

x1
x
x
x
y

eg2 - \n 最后:2

原文:

x2
x
x
x

实际:

x2
x
x
xy
y
y

预计:

x2
x
x
x

y

eg3 - \n 最后:3

原文:

x3
x
x
x


实际:

x3
x
x
xy
y
y
y

预计:

x3
x
x
x


y

首先,值得注意的是,Sublime Text 在搜索和替换功能中使用了 Boost 正则表达式引擎。

为了获得您期望的行为,您需要使用 \z 锚匹配 string/document.

\Z可以匹配末尾可选的换行数,见this Boost regex reference:

\z Matches at the end of a buffer only (the same as \').

\Z Matches a zero-width assertion consisting of an optional sequence of newlines at the end of a buffer: equivalent to the regular expression (?=\v*\z). Note that this is subtly different from Perl which behaves as if matching (?=\n?\z).

所以,这不是错误,这是 \Z 锚点的预期行为。