1

我正在使用rx函数从ELISP中的sexps生成正则表达式,但不知道如何生成用于 org-export-latex-classes的正则表达式“\\documentclass” :

    (rx "\\documentclass")
    (rx "\\" "documentclass")
    (rx (char "\\") "documentclass")

评估时分别给出以下输出:

    "\\\\documentclass"
    "\\\\documentclass"
    "[\\]documentclass"

“\\documentclass”是否等同于“[\\]documentclass”?---我认为是,但不确定。我可以使用 rx 生成前者吗?

编辑:虽然这个问题是有效的,但我意识到我的动机不是;因为 org-export-latex-classes 使用字符串而不是正则表达式。

4

1 回答 1

4

Emacs 需要\在字符串的双引号读取语法中进行转义,因此,当lisp 阅读器处理代码时,计算结果为包含单个字符"\\"的字符串对象\;因此,单个反斜杠是正则表达式引擎在使用该字符串对象时看到的内容。

但是,正则\表达式中的 a具有转义功能,这意味着正则\\表达式中的序列匹配单个\.

为了表示\\Emacs 字符串(读取语法)中的序列,每个反斜杠本身都必须通过在其前面加上反斜杠来进行转义。

因此"\\\\"计算为一个字符串,其中包含\\可以用作匹配单个\.

但是,在正则表达式字符替代序列中,反斜杠不会被转义;因此[\],由 string 表示"[\\]",匹配单个反斜杠 - 该单字符集的唯一可能匹配项。

所以用作正则表达式,字符串"\\\\""[\\]"匹配一样东西。

作为正则表达式的字符串实际上与没有反斜杠的字符串"\\documentclass"相同,因为它是在正则表达式中被转义的字符串(这是有效的,但当然是不必要的)。"documentclass"d

elisp 手册对此进行了如下解释:

`\' has two functions: it quotes the special characters (including
`\'), and it introduces additional special constructs.

Because `\' quotes special characters, `\$' is a regular
expression that matches only `$', and `\[' is a regular expression
that matches only `[', and so on.

Note that `\' also has special meaning in the read syntax of Lisp
strings (*note String Type::), and must be quoted with `\'.  For
example, the regular expression that matches the `\' character is
`\\'.  To write a Lisp string that contains the characters `\\',
Lisp syntax requires you to quote each `\' with another `\'.
Therefore, the read syntax for a regular expression matching `\'
is `"\\\\"'.

[...]

As a `\' is not special inside a character alternative, it can never
remove the special meaning of `-' or `]'.  So you should not quote
these characters when they have no special meaning either.  This would
not clarify anything, since backslashes can legitimately precede these
characters where they _have_ special meaning, as in `[^\]' (`"[^\\]"'
for Lisp string syntax), which matches any single character except a
backslash.

C-hig (elisp) Regexp Special RET

于 2012-06-02T16:33:52.867 回答