
org.parboiled.examples.doublequotedstring.DoubleQuotedString Maven / Gradle / Ivy
The newest version!
package org.parboiled.examples.doublequotedstring;
import org.parboiled.BaseParser;
import org.parboiled.Parboiled;
import org.parboiled.Rule;
import org.parboiled.annotations.BuildParseTree;
import org.parboiled.errors.ErrorUtils;
import org.parboiled.parserunners.TracingParseRunner;
import org.parboiled.support.ParseTreeUtils;
import org.parboiled.support.ParsingResult;
import java.util.Scanner;
/**
* A simple, double quoted string matching grammar
*
* This will match inputs such as:
*
*
* - {@code "hello world"};
* - {@code "hello \"world\""};
* - {@code ""};
* - {@code "\""}
*
*
* and so on.
*
* This parser builds the parse tree (the class is annotated using {@link
* BuildParseTree}) and uses a {@link TracingParseRunner} so that you can see
* the parsing process in action.
*
* This parser uses the {@code normal* (special normal*)*} pattern, often
* used in regexes to "unroll the loop". In this case:
*
*
* - {@code normal} is everything but a backslash or a double quote,
* - {@code special} is the character sequence {@code '\', '"'}.
*
*/
@BuildParseTree
public class DoubleQuotedString
extends BaseParser
{
Rule Normal()
{
return NoneOf("\\\"");
}
Rule Special()
{
return String("\\\"");
}
Rule NSN()
{
return Sequence(
ZeroOrMore(Normal()),
ZeroOrMore(Special(), ZeroOrMore(Normal()))
);
}
Rule DoubleQuotedString()
{
return Sequence('"', NSN(), '"', EOI);
}
public static void main(final String... args)
{
final DoubleQuotedString parser
= Parboiled.createParser(DoubleQuotedString.class);
final Scanner scanner = new Scanner(System.in);
ParsingResult> result;
String line;
while (true) {
System.out.print("Enter a value to test (empty to quit): ");
line = scanner.nextLine();
if (line.isEmpty())
break;
result = new TracingParseRunner(parser.DoubleQuotedString())
.run(line);
if (result.hasErrors()) {
System.out.println("Invalid input!");
System.out.println(ErrorUtils.printParseErrors(result));
} else {
System.out.println(ParseTreeUtils.printNodeTree(result));
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy