Search code examples
javascriptregexpeg

Difference between Peg.js and Regex


I'd like to use Peg.js to parse and validate something I've been doing with Regular Expressions and am struggling with the syntax.

My Peg.js program is :

start = (var / other) cr 
d:var {return d.join('')}

var = [^(?=.{1,32}$)([a-zA-Z_][a-zA-Z0-9_]*)$] {return "OK"}
other = . {return "NOT OK"}
cr = "\n"

And I am testing it with the following text:

test1
no space
1var
_temp
ReallyLongNameisInvalidandLongerthan32
IncorrectChars!!asdf
_
underscore_is_fine_

I expect the results YES, NO, NO, YES, NO, NO, YES, YES, but am going round in circles with the regular expression errors that would normally work fine.


Solution

  • When a peg rule fails to match, it will try to match the next rule until it has run out of rules. Try something along these lines:

    start = line+
    
    line = d:(var / other)
    {
        return d;
    }
    
    var = v:$([a-zA-Z_][a-zA-Z0-9_]*) cr
    {
        if (v.length > 32) {
            return "no";
        } else {
            return "yes";
        }
    }
    
    other = [^\n]+ cr
    {
        return "no";
    }
    
    cr = "\n"
    

    Output:

    [
       "yes",
       "no",
       "no",
       "yes",
       "no",
       "no",
       "yes",
       "yes"
    ]