ANTLR4 lexer matches a hyphenated identifier instead of the minus operator
11:02 30 Sep 2026

I am writing an ANTLR4 grammar for a small expression language.

Identifiers may contain letters, digits and hyphens, for example:

user-name
total-value

At the same time, - is also a binary subtraction operator:

total - value

My lexer currently contains:

IDENTIFIER
    : [a-zA-Z] [a-zA-Z0-9-]*
    ;

MINUS
    : '-'
    ;

NUMBER
    : [0-9]+
    ;

WS
    : [ \t\r\n]+ -> skip
    ;

The parser contains:

expression
    : expression MINUS expression
    | IDENTIFIER
    | NUMBER
    ;

For this input:

total-value

I expected ANTLR to tokenize it as:

IDENTIFIER MINUS IDENTIFIER

but it is tokenized as a single IDENTIFIER.

I understand that ANTLR's lexer chooses the longest matching token, but I need both forms to be valid:

user-name

as an identifier, and

user - name

as a subtraction expression.

How should the grammar be structured so that the parser can distinguish these two cases without incorrectly consuming - as part of the identifier?

parsing antlr4 grammar language-design lexer