Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Parse Multiple Lines Of Integers With nom In Rust

Code

//! ```cargo
//! [dependencies]
//! nom = "7.1.3"
//! ```

use nom::branch::alt;
use nom::character::complete::i64;
use nom::character::complete::line_ending;
use nom::character::complete::space1;
use nom::combinator::eof;
use nom::multi::many1;
use nom::multi::separated_list1;
use nom::sequence::pair;
use nom::IResult;
use nom::Parser;

fn main() {

    let input = "1 2 3 4 5
-9 -8 234 123123 433
28927 -234";

    let data = parse(input).unwrap().1;
    dbg!(data);
}

fn parse(source: &str) -> IResult<&str, Vec<Vec<i64>>> {
    let (source, results) = many1(
        pair(
            separated_list1(space1, i64),
            alt((line_ending, eof)),
        )
        .map(|(x, _)| x),
    )(source)?;
    Ok((source, results))
}

Results

[neopolitan_code_run:22] data = 
[
    [ 1, 2, 3, 4, 5 ],
    [ -9, -8, 234, 123123, 433 ],
    [ 28927, -234 ],
]

This is what I'm using to parse lines of integers for Advent Of Code. It creates a Vec of Vecs of i64s. This includes negative values as well as positive.