BNFParserJava is a Backus-Naur Form Framework for JAVA written by Mike Friesen in Java and released under the Apache 2 Open Source License.
An Objective-C version is also available.
BNFParserJava was inspired by the framework ParseKit by Todd Ditchendorf.
The BNFParserJava Framework offers 3 basic services of general interest to developers:
-
String Tokenization via the
BNFTokenizerFactory
andBNFToken
classes -
Property Key/Value mapper via
PropertyParser
-
Text Parsing via Grammars via BNFParser see grammar syntax
The string tokenizer breaks down any string into a series of letter/number/symbols for easy processing.
String text = "The cow jumped over the moon!";
BNFTokenizerFactory factory = new BNFTokenizerFactoryImpl();
BNFToken token = factory.tokens(text);
while (token != null) {
System.out.println("TOKEN " + token.getStringValue());
token = token.getNextToken();
}
Uses the string tokenizer to parse a string and create key/value mapping based on the '='
symbol.
String text = "sample key = sample value";
PropertyParser parser = new PropertyParser();
Map<String, String> keyValueMap = parser.parse(text);
Assert.assertNotNull(keyValueMap.get("sample key"));
BNFParser currently only ships with a JSON grammar so the example are based on that.
// Create String Tokens
String text = "{ \"key\":\"value\"}";
BNFTokenizerFactory tokenizerFactory = new BNFTokenizerFactoryImpl();
BNFToken token = tokenizerFactory.tokens(text);
// Create Backus-Naur Form State Definitions
BNFSequenceFactory factory = new BNFSequenceFactoryImpl();
Map<String, List<BNFSequence>> map = sdf.json();
// Run Tokens through Parser
BNFParser parser = new BNFParserImpl(map);
BNFParseResult result = parser.parse(token);
// Verify results
// verify text passes grammar:
Assert.assertTrue(result.isSuccess()); // verify text passes grammar
// the "first" token, same as the token returned from the tokenizer factory:
Assert.assertNotNull(result.getTop());
// the "first" error token, this token and any afterwards are considered to not have passed the grammar:
Assert.assertNull(result.getError());
For bugs, questions and discussions please use the Github Issues.
We love contributions! If you'd like to contribute please submit a pull request via Github.
This library is distributed under the Apache 2 Open Source License.