Emacs - Lisp 中的正则表达式需要双重转义 - 为什么? [英] Emacs - regular expressions in Lisp need to be double-escaped - why?
问题描述
我一直在玩 emacs lisp,我想写一个小函数来进行正则表达式搜索和替换.我花了很长时间让正则表达式正常工作,因为我没有意识到在编写 lisp 代码时所有特殊字符都需要双重转义(但在交互使用 query-replace-regexp 时不需要!).
I've been playing around with emacs lisp, and I wanted to write a little function to do a regular expression search and replace. I had a heck of a time getting the regular expression to work correctly because I didn't realize that all the special characters need to be double escaped when writing lisp code (but not when using query-replace-regexp interactively!).
例如,交互地使用 query-replace-regexp 你可以使用
So for example, using query-replace-regexp interactively you can use
^(.*)[ ]-.*$
但是在编写elisp代码时,您需要像这样双重转义所有内容:
but when writing elisp code you need to double escape everything like so:
^\(.*\)[ ]-.*$
我终于在 Steve Yegge 文章中找到了对此的引用,但是我想知道有没有人知道这是为什么?
I finally found a reference to this in a Steve Yegge article, but I was wondering if anyone knew why this is?
推荐答案
这是因为您需要对字符串中的反斜杠进行转义.如果不转义字符串中(
的反斜杠,结果只是(
It's because you need to escape backslashes in strings. If you don't escape the backslash of (
in the string, it turns out to be just (
这篇关于Emacs - Lisp 中的正则表达式需要双重转义 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!