1

I am trying to extract the function name from a function call. For example:

(let ((str "(test-func"))
  (if (string-match "^(\\s_+" str)
      (message "ok")
    (message "no match")))

But this gives "no match".. (For simplicity I reduced str to the start of the real string. A real string could be for example "(test-func a b)"

I think the problem is the \s_ symbol constituent regex..

  • 1
    In an empty buffer, type (test-func -- then type M-x re-builder -- then in between the double quotation marks in the re-builder buffer, type your proposed regexp and see if it works. If it doesn't, then work on the regexp until re-builder shows the highlighting is correct -- e.g., paste the regexp by abo-abo and see the difference. – lawlist Jan 30 '15 at 9:16
  • 1
    Not answering your question directly: why are you trying to parse the code yourself (instead of using Emacs' own Lisp parser)? Obviously, you can't parse Emacs Lisp with regular grammar, but, again, there might be some legitimate uses, this is why this is posed as a question. – wvxvw Jan 30 '15 at 9:20
  • Quoting from elsewhere, in case it helps clarify this Q&A for anyone: "A "symbol" may contain both word-constituent characters and symbol-constituent characters. But the terms "symbol-constituent [character]" and "word-constituent [character]" themselves are very specifically about their own mutually-exclusive syntax classes, and there is no similar term which refers to a character from either syntax class." – phils Jan 30 '15 at 16:01
1

You want:

(let ((str "(test-func"))
  (if (string-match "^(\\(?:\\s_\\|\\sw\\)+" str)
      (message "ok")
    (message "no match")))

\\s_ will match stuff like -, while \\sw will actually match the alnum stuff.

update

There's also a trick using two C functions (probably efficient), if you're operating on a buffer. With point right after (:

(read (point-marker))
=> test-func

The return result is a Lisp symbol, which might readily be useful.

  • This will also match digits (as in lists). – wvxvw Jan 30 '15 at 9:17
  • \\sw matches digits. – abo-abo Jan 30 '15 at 9:20
  • Well, this depends on what exactly OP means by his question: is it "how to match a function call and to extract the name of the function being called" - in which case your regexp gives extra matches, or "given that the string is know to be a function call, how to extract its name", in which case that's fine. – wvxvw Jan 30 '15 at 9:24
  • Thanks @abo-abo. I also found this regex : "\\(\\w\\|\\s_\\)+", see gnu.org/software/emacs/manual/html_node/eintr/Syntax.html – Håkon Hægland Jan 30 '15 at 9:24
  • 1
    \\w instead of \\sw will fail for (str "(test-\ func123"), which is a valid symbol. – abo-abo Jan 30 '15 at 9:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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