Matching anything with Clojure Instaparse

237 Views Asked by At

I want to parse a simple language which basically has a couple of special glyphs or characters in front of a line of text. If it doesn't have these, then the line of text is just taken as data.

For example :

+ hfflsdjf dslfhsldfh sdlfkh sdlfkhs 
! sdlfkhsdl sdfb sldflsdfh sldkfh sd
dsf sldfbbsf sdfjbs kfjbsd kjbsdf 

The first and second lines have special meanings because of the + and ! at the front, the rest of the line is data to that instruction. But the third line is just data.

How could I express this in Instaparse?

Basically I want to say any string that isn't matched by any of the other rules should be matched by the DATA terminal.

1

There are 1 best solutions below

0
akond On
(def as-and-bs
    (insta/parser
        "<text> = (rubbish | op ) *
         <op> = plus | bang
         <line> = #'[^\n]*(\n|$)'
         rubbish = line
         plus = '+' line
         bang = '!' line"))

(as-and-bs "+ abc\n! def\ncu ")
;=> ([:plus "+" " abc\n"] [:bang "!" " def\n"] [:rubbish "cu "])