How can I use PEGjs for validation instead of parsing?

I have the following PEGjs working:

NameStartChar = ":" / [A-Z] / "_" / [a-z] / [\u00C0-\u00D6] / [\u00D8-\u00F6] / [\u00F8-\u02FF] / [\u0370-\u037D] /
                [\u037F-\u1FFF] / [\u200C-\u200D] / [\u2070-\u218F] / [\u2C00-\u2FEF] / [\u3001-\uD7FF] /
                [\uF900-\uFDCF] / [\uFDF0-\uFFFD] / [\uD800-\uDB7F][\uDC00-\uDFFF]

NameChar = NameStartChar / "-" / "." / [0-9] / "\u00B7" / [\u0300-\u036F] / [\u203F-\u2040]

Name = NameStartChar NameChar*

      

I would like to somehow get true

if my input string matches Name

and false

otherwise. I also don't need to disassemble the component parts.

However, PEGjs really wants to throw an exception if the match fails.

I could of course wrap it in try / catch, but I would rather avoid that. And I would also like to avoid collecting the parsed components (i.e. I don't need it ["a", ["b", "c", "d"]]

when mapping "abcd"

, I just need it true

).

Is there a hidden PEGjs function that will make this work? Maybe clever action or innovative use of combinators?

Or maybe I should be using a completely different tool and not a parser generator? If so, does anyone know what I should be using?

+3


source to share


3 answers


We can use Name { return true } / { return false }

to get an expression that will return true if the rule matches. Then we can add !.

to check that we are at the end of the input for the case true

, and. * To skip to the end on a false case. So we get:



ValidateName = Name !. { return true } / .* { return false }

      

+4


source


The language of the names you define seems to be regular to me, so you can do it with a regular expression. Depending on the language you are using, you call the function match or find to validate the input.

Don't forget to put the start and end of your string bindings so that it matches all the input, like



^(:|[A-Z]|_|etc)(:|[A-Z]|_|etc|-|\.|[0-9]|etc)*$

      

0


source


ValidateName = Name { return true } / { return false }

      

If you want to validate input without advancing the position of the parser with a subexpression, you can use &Name

.

-1


source







All Articles