java - Parsing negative numbers with jparsec -
java - Parsing negative numbers with jparsec -
using jparsec, i'm trying parse numbers may or may not negative:
@test public void canparseintegervalues() { assertequals(0, valueparser.parser.parse("0")); assertequals(276, valueparser.parser.parse("276")); assertequals(-3874, valueparser.parser.parse("-3874")); }
i've not been able figure out how declare parser
. i've tried:
private static final parser<integer> integer_value_parser = terminals.integerliteral.tokenizer .map(new map<fragment, integer>() { @override public integer map(fragment from) { homecoming integer.valueof(from.text()); } });
this doesn't work because terminals.integerliteral.tokenizer
not accommodate minus sign. next, tried:
private static final parser<integer> integer_value_parser = parsers.sequence( scanners.string("-").optional().token(), terminals.integerliteral.tokenizer .map(new map<fragment, integer>() { @override public integer map(fragment from) { homecoming integer.valueof(from.text()); } }));
this doesn't work because negative sign discarded , map function never sees it.
can tell me how correctly parse integers may or may not positive using jparsec?
edit: found way it, find hard believe best way:
private static final parser<integer> integer_value_parser = parsers.sequence( scanners.string("-").many(), terminals.integerliteral.tokenizer, new map2<list<void>, fragment, integer>() { @override public integer map(list<void> from1, fragment from2) { boolean isnegative = (from1.size() % 2) == 1; if (isnegative) { homecoming -1 * integer.valueof(from2.text()); } else { homecoming integer.valueof(from2.text()); } } });
you can have @ calculator
class in jparsec's examples: https://github.com/abailly/jparsec/blob/master/jparsec-examples/src/main/java/org/codehaus/jparsec/examples/calculator/calculator.java here negative integers handled integers on prefix -
operator has been applied.
alternatively can declare pattern comprising minus sign:
public void test() { pattern regex = patterns.regex("-?\\d+"); parser<integer> integer = scanners.pattern(regex, "integer").source().map(new map<string, integer>() { @override public integer map(string s) { homecoming integer.parseint(s); } }); assertequals(-42, (int) integer.parse("-42")); }
hth
arnaud
java parsing jparsec
Comments
Post a Comment