4

In one of my older elisp code snippets, I was surprised to find the below (and that even worked fine all this time!)

The problem (which should have been) is that I did not escape the back-slashes in the regexp string: "\*abc\*"

(string-match-p "\*abc\*" "def*abc*")

So I then fixed the expression to below.

(string-match-p "\\*abc\\*" "def*abc*")

Both of the above expressions yield the same result.

Question: Why did the incorrect way work here?

1 Answer 1

6
(string-match-p "\*abc\*" "def*abc*")

is equivalent to

(string-match-p "*abc*" "def*abc*")

which matches because (1) the first * is matched literally against the first * in the second argument and (2) the second * means zero or more occurrences of c, which matches the one c occurrence.

8
  • I had to read your answer 3 times to finally get it (not your fault, this is intricated material). Maybe you could mention that you swapped the regexps (the 2nd from the question is 1st in the answer), and that you give here the version after the strings were evaluated (so not real elisp).
    – T. Verron
    Jun 26, 2015 at 16:28
  • 2
    @Drew Thanks. I was surprised that that literal * matching happened. Jun 26, 2015 at 16:32
  • 1
    Just found this from elisp manual: For historical compatibility, special characters are treated as ordinary ones if they are in contexts where their special meanings make no sense. For example, ‘*foo’ treats ‘*’ as ordinary since there is no preceding expression on which the ‘*’ can act. Jun 26, 2015 at 18:24
  • @kaushalmodi I was surprised too, but it seems that grep behaves in the same way.
    – T. Verron
    Jun 27, 2015 at 15:34
  • @T.Verron: Sorry, but I don't know what you mean about regexps being swapped or out of order. The first string-match-p sexp I show is the same as the first one shown in the question. The second one I show is not in the question - I show it to point out that the backslashes have no effect, and that if you evaluate the second one it DTRT for the reason I gave: the first * is matched literally.
    – Drew
    Jun 27, 2015 at 15:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.