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?
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.
Sign up to join this communityTry 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.)
(font-lock-add-keywords 'sql-mode '( ("\[[^]]*\]" . font-lock-function-name-face) ))
does not work. How do I include ]
char in a list of "excluded chars"?
[
. Did you try "\[^]]*\]
? That excludes ]
. It makes little sense to write \[[^]\]
, which says match either [
or anything other than newline and ]
. The second set of chars includes the first.
"\[[^]]*\]"
applies only to empty square brackets. I think this regexp means: "looking for something that starts with square bracket, followed by any number of any chars but new line and square bracket, and ends with square bracket as well".
\[
and \]
represents one character - any character of those specified. You follow that by *
, meaning zero or more of them. Nothing in what you wrote specifies [
followed by... Please consult the Elisp manual, node Syntax of Regexps and its subnodes.