Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Parsing expression grammar
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== More examples === The following recursive rule matches standard C-style if/then/else statements in such a way that the optional "else" clause always binds to the innermost "if", because of the implicit prioritization of the '/' operator. (In a [[context-free grammar]], this construct yields the classic [[dangling else|dangling else ambiguity]].) <syntaxhighlight lang="peg"> S β 'if' C 'then' S 'else' S / 'if' C 'then' S </syntaxhighlight> The following recursive rule matches Pascal-style nested comment syntax, {{code|(* which can (* nest *) like this *)}}. Recall that {{code|.|peg}} matches any single character. <syntaxhighlight lang="peg"> C β Begin N* End Begin β '(*' End β '*)' N β C / (!Begin !End .) </syntaxhighlight> The parsing expression {{code|2=peg|foo &(bar)}} matches and consumes the text "foo" but only if it is followed by the text "bar". The parsing expression {{code|2=peg|foo !(bar)}} matches the text "foo" but only if it is ''not'' followed by the text "bar". The expression {{code|2=peg|!(a+ b) a}} matches a single "a" but only if it is not part of an arbitrarily long sequence of a's followed by a b. The parsing expression {{code|2=peg|('a'/'b')*}} matches and consumes an arbitrary-length sequence of a's and b's. The [[Formal grammar#The syntax of grammars|production rule]] {{code|2=peg|S β 'a' ''S''? 'b'}} describes the simple [[context-free language|context-free]] "matching language" <math> \{ a^n b^n : n \ge 1 \} </math>. The following parsing expression grammar describes the classic non-context-free language <math> \{ a^n b^n c^n : n \ge 1 \} </math>: <syntaxhighlight lang="peg"> S β &(A 'c') 'a'+ B !. A β 'a' A? 'b' B β 'b' B? 'c' </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)