blynn / nex

Lexer for Go
http://cs.stanford.edu/~blynn/nex/
GNU General Public License v3.0
416 stars 47 forks source link

Solved: How to match single line comments (using negation!) #45

Closed purpleidea closed 7 years ago

purpleidea commented 7 years ago

I previously couldn't figure out how to match single line comments. Now solved, so I'm opening and closing this issue so it will get seen as reference for future users.

Match the single line comment:

/#[^\n]*/
    {   // this matches a (#) pound char followed by any
        // number of chars that aren't the (\n) newline!
        s := yylex.Text()
        lval.str = s[1:len(s)] // remove the leading #
        log.Printf("lang: lexer: comment: `%s`", lval.str)
        //return COMMENT // skip return to avoid parsing
    }

The trick was the ^ negates the newline char, which matches all the junk you want, up until the newline. In the source this is the negate property.

Sadly it seems as if all the regexp code was copy+pasted incompletely from the golang lib, and as a result, a lot of standard regexp things are missing such as :alpha: for example.

Hope this hidden tutorial helped you!