BNF Syntax Checker
Write BNF production rules and test whether strings belong to the language. Edit the grammar, change the start symbol, and add test strings to explore context-free grammars. Spec reference: §4.4.3.
📖 Learn Step-by-StepA simple integer: an optional sign followed by one or more digits.
BNF syntax:
<name> — non-terminal (variable)
::= — "is defined as"
| — separates alternatives ("or")
Anything not in angle brackets is a terminal (literal character)
Test Strings
BNF / Context-Free Grammar Practice Questions
Given the BNF rule <digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9, how many alternatives does this rule have?
The grammar is: <S> ::= a<S>b | ab. What is the length of the shortest string that can be derived from <S>?
Using the grammar <S> ::= a<S>b | ab, how many derivation steps are needed to produce the string "aaabbb"?
A grammar has: <expr> ::= <term> | <expr>+<term>, <term> ::= <digit>, <digit> ::= 0|1|...|9. How many non-terminal symbols are in this grammar?
A BNF grammar generates the language {aⁿbⁿ | n ≥ 1}. Using the rule <S> ::= a<S>b | ab, what is the length of the string generated after exactly 5 derivation steps?
Quick reference — BNF & Context-Free Grammars
What is BNF?
Backus–Naur Form (BNF) is a notation for describing the syntax of context-free grammars. Each rule defines how a non-terminal can be expanded into a sequence of terminals and/or non-terminals.
BNF notation
| <name> | Non-terminal (a variable that can be expanded) |
| ::= | "Is defined as" |
| | | Separates alternatives |
| terminals | Literal characters that appear in the final string |
Context-free vs regular
Context-free grammars (CFGs) are more powerful than regular expressions. CFGs can describe languages like aⁿbⁿ (matched parentheses) which regular expressions cannot. However, CFGs cannot describe all possible languages — for example, aⁿbⁿcⁿ requires a context-sensitive grammar.
Derivation
A derivation shows how a string is produced from the start symbol by repeatedly replacing non-terminals using the production rules. A leftmost derivation always expands the leftmost non-terminal first.
AQA exam tips
- Be able to read BNF and determine if a string is valid
- Be able to write BNF rules for a given language
- Show derivations step by step
- Know the difference between BNF and EBNF (Extended BNF uses { } for repetition and [ ] for optional)