diff --git a/doc/nom_recipes.md b/doc/nom_recipes.md index e8626344a..95893cef1 100644 --- a/doc/nom_recipes.md +++ b/doc/nom_recipes.md @@ -4,6 +4,7 @@ These are short recipes for accomplishing common tasks with nom. * [Whitespace](#whitespace) + [Wrapper combinators that eat whitespace before and after a parser](#wrapper-combinators-that-eat-whitespace-before-and-after-a-parser) + + [Ignore empty lines](#ignore-empty-lines) * [Comments](#comments) + [`// C++/EOL-style comments`](#-ceol-style-comments) + [`/* C-style comments */`](#-c-style-comments-) @@ -52,6 +53,35 @@ Likewise, the eat only leading whitespace, replace `delimited(...)` with `preced &inner)`. You can use your own parser instead of `multispace0` if you want to skip a different set of lexemes. +### Ignore empty lines +```rust +use nom::{ + branch::alt, + combinator::map, + multi::{separated_list1, many1}, + IResult, + InputLength, +}; + +pub fn separated_lines_ignore( + sep: impl FnMut(I) -> IResult, + f: impl FnMut(I) -> IResult, + ignore: impl FnMut(I) -> IResult, +) -> impl FnMut(I) -> IResult> +{ + map( + separated_list1( + many1(sep), + alt(( + map(f, |l| Some(l)), + map(ignore, |_| None) + )) + ), + |ls| ls.into_iter().flatten().collect(), + ) +} +``` + ## Comments ### `// C++/EOL-style comments`