Search code examples
javascriptpeg

PEG.js matching word from Array


I have problem with PEG.js and matching words.

It looks like this: Words = "stack"/"overflow"/"stackoverflow" - when I try to match "stackoverflow" it shows error Expected end of input but "o" found. so it found stack and thought it was end - overflow was left.

You can try it here: https://pegjs.org/online and paste:

Text = Word Word = "stack"/"overflow"/"stackoverflow" and try with word "stackoverflow"

I don't wont to change words in array.

Best Regards.


Solution

  • PegJS tries to match the first value. Only if this does not succeed, it will try the second one and so on. As in your case stack can be matched, it will not continue trying to match anything else.

    This problem will oftentimes appear, when one match is a prefix of another one. In such cases, you should start the list with the "longer" terms and put the prefixes towards the end:

    Text = Word
    Word = "stackoverflow"/"stack"/"overflow"
    

    You could also match for multiple words. In this case both stack and overflow will get matched, but not stackoverflow.

    Text = Word*
    Word = "stack"/"overflow"/"stackoverflow"