In the Emacs *scratch*
buffer, I get different results when I use the same regular expression as a variable compared to a literal:
(setq splitter-string "9:20")
"9:20"
(string-match "[0-9]?[0-9]:[0-9][0-9]" splitter-string)
0
(defvar org-clock-split-absolute-time-regexp "[0-9]?[0-9]:[0-9][0-9]"
"Regular expression to match an absolute time to split at.")
org-clock-split-absolute-time-regexp
(string-match org-clock-split-absolute-time-regexp splitter-string)
nil
What is the difference between a variable and a literal for regular expressions?
Update: The problem stems from the inability to overwrite a variable defined with defvar
, as below in the scratch buffer:
(defvar pattern "some pattern"
"Some regular expression")
pattern
pattern
"some pattern"
(defvar pattern "[a-z]*"
"Some regular expression")
pattern
pattern
"some pattern"
(string-match "[a-z]*" "abcdefg")
0
(string-match pattern "abcdefg")
nil
I would not do this in final code, but may do it in the scratch buffer during development. The problem is about defvar
, and a duplicate of this question, and not about regular expressions (I knew about the different syntaxes with re-builder
and suspected it was about that).
defvar
clobbered an existing value of the variable, loading (or reloading) a library would trash the user's configuration for it. It's important that users can(setq VAR VALUE)
even when the library which defines VAR hasn't yet been loaded.eval-defun
--C-M-x
by default -- to evaluate thedefvar
form, it will set the value. (n.b. the same things apply todefcustom
as well.)defconst
instead ofdefvar
, and the value will be set every time thedefconst
is evaluated.setq
(or any other way of "setting a variable") to update the value. (And unless you are working on the library which defines the variable, this is all you should be doing.)