'How can I make an ANTLR rule that matches a line of characters containing a specific character only once, at any position in the line?

I am new to writing grammar in ANTLR, and I am not sure how to make the rule I want here. Suppose a line of characters could possibly be something like:

a b  c 1 e :  d   g e 3 s 5 b 7 d   r : f : 2 v : 2

But could also look like:

g j : f 1 h k 6 u s h u 5 r c b 0 u k = x v 

which is what I am looking for.

So, a line could be made up of any number of letters, numbers, and : symbols in any order, and any white space is ignored. I need an ANTLR rule that matches a line that looks like these, except only has one : symbol, which can be located any position in the line. How can I do this?



Solution 1:[1]

Depending on the rest of your lexer rules, you might try something like this:

WholeLineWithOneColon
 : ~[:\r\n]* ':' ~[:\r\n]*
 ;

Note that this need not match an entire line (or even start at the beginning of the line), because the matching of ANTLR's lexer rules are dependent on other rules that possibly match more than the rule I now gave an example of.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bart Kiers