The sheer number of backslashes my regexps require is pretty crazy. Does elisp have regexp literals, so I can write something like
rx"some\(regexp\)"
instead of
"some\\(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 communityThe sheer number of backslashes my regexps require is pretty crazy. Does elisp have regexp literals, so I can write something like
rx"some\(regexp\)"
instead of
"some\\(regexp\\)"
One option is to use the rx
macro to construct your expressions using sexps.
Your example becomes (rx "some" (group "regexp"))
Here are a couple more examples from the commentary section in rx.el, to get an idea of how rx
works:
This ^;;\\s-*\n\\|^\n
becomes
(rx (or (and line-start ";;" (0+ space) ?\n)
(and line-start ?\n)))
This [ \t\n]*:\\([^:]+\\|$\\)
becomes
(rx (and (zero-or-more (in " \t\n")) ":"
(submatch (or line-end (one-or-more (not (any ?:)))))))
rx
syntax, which makes them easier to maintain. Imho, for similar cases, rx syntax by itself makes elisp a well-worthy substitute for perl python, ruby, etc. Thank you.
– gsl
Apr 10 '16 at 7:37
No it does not have regexp literals, but many find pcre2el to be a helpful alternative.
Specifically using it from elisp like this:
(rxt-pcre-to-elisp "(abc|def)\\w+\\d+")
;; => "\\(\\(?:abc\\|def\\)\\)[_[:alnum:]]+[[:digit:]]+"
\\|
,\\(
, and\\)
. Unfortunately, in many themes this isn't visible. You can overridefont-lock-regexp-grouping-backslash
andfont-lock-regexp-grouping-construct
to make this more distinct. – Lindydancer Feb 9 '15 at 5:58