I tried these two, but none of them worked.
(if (looking-at "\[") (insert "f"))
(if (looking-at "[") (insert "f"))
How can I escape square brackets in emacs regexp?
I tried these two, but none of them worked.
(if (looking-at "\[") (insert "f"))
(if (looking-at "[") (insert "f"))
How can I escape square brackets in emacs regexp?
Try this:
(if (looking-at "\\[") (insert "f"))
Usually you will need to escape your escaping backslash. This tutorial has a short explanation of the "double backslash".
When in doubt, I always use the built-in re-builder
. If you try this on a buffer with [
in it, you will find that "\\["
will match them. Pressing C-c C-w
in the re-builder
will copy the regular expression to your kill-ring to yank back into the function you are working on.
All you need is this: (if (looking-at "[[]") (insert "f"))
.
In general, "special" regexp characters are not special within brackets.
See the Elisp manual, node Regexp Special. It tells you this about special chars and bracketed char classes:
Note also that the usual regexp special characters are not special inside a character alternative. A completely different set of characters is special inside character alternatives: ‘]’, ‘-’ and ‘^’.
To include a ‘]’ in a character alternative, you must make it the first character. For example, ‘[]a]’ matches ‘]’ or ‘a’. To include a ‘-’, write ‘-’ as the first or last character of the character alternative, or put it after a range. Thus, ‘[]-]’ matches both ‘]’ and ‘-’. (As explained below, you cannot use ‘]’ to include a ‘]’ inside a character alternative, since ‘\’ is not special there.)