Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs - regular expressions in Lisp need to be double-escaped - why?

Tags:

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?

like image 299
Kevin Tighe Avatar asked Feb 11 '09 21:02

Kevin Tighe


People also ask

What should be escaped in regex?

Operators: * , + , ? , | Anchors: ^ , $ Others: . , \ In order to use a literal ^ at the start or a literal $ at the end of a regex, the character must be escaped.

Do I need to escape period in regex?

(dot) metacharacter, and can match any single character (letter, digit, whitespace, everything). You may notice that this actually overrides the matching of the period character, so in order to specifically match a period, you need to escape the dot by using a slash \. accordingly.

Do we need to escape Colon in regex?

Colon does not have special meaning in a character class and does not need to be escaped.


1 Answers

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 (

like image 83
scottfrazer Avatar answered Sep 22 '22 05:09

scottfrazer