zevv / npeg

PEGs for Nim, another take
MIT License
330 stars 22 forks source link

lazy matching #35

Closed hamidb80 closed 3 years ago

hamidb80 commented 3 years ago

hey,

I remember in REGEX when I can write (.+) bag and it matches the "faded blue bag" [it's a very normal regex pattern]

but I can't do something like this in npeg.

const parser = peg("main", data: ...):
  main  <-   >*{ 'a' .. 'z', ' ' }  * " bags":
    echo "matched: ", $1
zevv commented 3 years ago

Well, PEGs are not regular expressions, and greedyness is one of the things in which they differ.

PEG grammars are greedy by default and will chomp along as long as the input match the pattern, so you need to be explicit in what you want to match. This is not specific to NPeg, but goes for PEGs in general.

In your example that would be something like:

const parser = peg("main"):
  word <- +{'a'..'z'}
  main <- >(word * ' ' * word) * " bags":      
    echo "matched: ", $1