简单的定界符解析器

Simple delimiter parser

我正在尝试 PetitParser 解析以逗号分隔的简单整数列表。例如:“1、2、3、4”

我尝试创建一个整数解析器,然后使用 delimitedBy 方法。

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

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

这个 returns 一个包含已解析整数和分隔符的列表。 例如:[1,2,3,4]

有没有办法从结果中排除定界符?

这里是一个没有任何外部库的例子:

public static void main(String args[]) {
    // source String
    String delimitedNumbers = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10";
    // split this String by its delimiter, a comma here
    String[] delimitedNumbersSplit = delimitedNumbers.split(",");

    // provide a data structure that holds numbers (integers) only
    List<Integer> numberList = new ArrayList<>();

    // for each part of the split list
    for (String num : delimitedNumbersSplit) {
        // remove all whitespaces and parse the number
        int n = Integer.parseInt(num.trim());
        // add the number to the list of numbers
        numberList.add(n);
    }

    // then create the representation you want to print
    StringBuilder sb = new StringBuilder();
    // [Java 8] concatenate the numbers to a String that delimits by whitespace
    numberList.forEach(number -> sb.append(number).append(" "));
    // then remove the trailing whitespace
    String numbersWithoutCommas = sb.toString();
    numbersWithoutCommas = numbersWithoutCommas.substring(0, numbersWithoutCommas.length() - 1);
    // and print the result
    System.out.println(numbersWithoutCommas);
}

Note that you don't need to trim() the results of the split String if you have a list without whitespaces.

如果您需要 PetitParser 库,您必须在其文档中查找如何使用它。

通过更多的代码,我得到了没有分隔符的结果:

Parser number = digit().plus().flatten().trim()
        .map((String value) -> Integer.parseInt(value));

Parser next = of(',').seq(number).map((List<?> input) -> input.get(1)).star();

Parser parser = number.seq(next).map((List<List<?>> input) -> {
    List<Object> result = new ArrayList<>();
    result.add(input.get(0));
    result.addAll(input.get(1));
    return result;
});

是的,有:

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

获取withoutSeparators()导入import static org.petitparser.utils.Functions.withoutSeparators;.