Search code examples
regexemacsemacs-faces

font-lock-add-keywords regexp for C++ operators


I have a regexp that finds and highlights operators in C++ but I can't for the life of me work out how to match operator[] using regexp. The usual trick of escaping the characters doesn't seem to work, it merely ends matching.

    (font-lock-add-keywords
     nil '(
       ;; operators
       ("[~^&\|!<>:=,.\\+*/%-]" . font-lock-keyword-face) ))

My second (incomplete) attempt using regexp-builder and moving escaped symbols to the end of the match got me the opening brace:

    ("[~^=<>&/.,\[\|\*\+\-]" . font-lock-keyword-face)

but adding \] or moving \[ kills any matching. What am I missing?


Solution

  • To match a literal ], put it right after the opening [:

    "[]~^=<>&/.,\[\|\*\+\-]"
    

    Since an empty character choice wouldn't make any sense in a regexp, this combination is given the alternative interpretation of matching an actual ].