javapetitparser

Simple delimiter parser


I'm trying out PetitParser for parsing a simple integer list delimited by commas. For example: "1, 2, 3, 4"

I tried creating a integer parser and then use the delimitedBy method.

Parser integerParser = digit().plus().flatten().trim().map((String value) -> Integer.parseInt(value));
Parser listParser = integerParser.delimitedBy(of(','));

List<Integer> list = listParser.parse(input).get();

This returns a list with the parsed integers but also the delimiters. For example: [1, ,, 2, ,, 3, ,, 4]

Is there a way to exclude the delimiters from the result?


Solution

  • Yes, there is:

    Parser listParser = integerParser
        .delimitedBy(of(','))
        .map(withoutSeparators());
    

    To get withoutSeparators() import import static org.petitparser.utils.Functions.withoutSeparators;.