0

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.

user5072412
  • 187
  • 1
  • 10
  • ...and what are those errors exactly? – Tim Biegeleisen Sep 27 '18 at 07:05
  • Ahh, sorry, I should say I was testing in https://pegjs.org/online, the error I get is :Line 4, column 44: Expected "!", "$", "&", "(", ".", "/", "/*", "//", ";", character class, code block, comment, end of line, identifier, literal, or whitespace but ")" found. – user5072412 Sep 27 '18 at 09:27

1 Answers1

1

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"
]
Josh Voigts
  • 4,114
  • 1
  • 18
  • 43