Emacs - Lisp中的正则表达式需要双重转义 - 为什么? [英] Emacs - regular expressions in Lisp need to be double-escaped - why?

查看:101
本文介绍了Emacs - Lisp中的正则表达式需要双重转义 - 为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩emacs lisp,我想写一个小功能来进行正则表达式搜索和替换。我有一段时间让正则表达式正常工作,因为我没有意识到所有的特殊字符在编写lisp代码时都需要双重转义(但是当交互使用query-replace-regexp时不需要)。



所以例如,使用交互式的query-replace-regexp可以使用

  ^ \(。* \)[\t]  - 。* $ 

但是当编写elisp代码时,您需要双重转义所有这样的东西:

  ^ \\(。* \\ )[\t]  - 。* $ 

我终于在Steve Yegge找到了一个参考文章,但是我是想知道有没有人知道为什么会这样?

解决方案

这是因为您需要在字符串中转义反斜杠。如果你没有逃避\的反斜杠(在字符串中,它原来只是(


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!).

So for example, using query-replace-regexp interactively you can use

^\(.*\)[\t]-.*$

but when writing elisp code you need to double escape everything like so:

^\\(.*\\)[\t]-.*$  

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆