TextBlocks
A simple crate for parsing text blocks. Can be used to parse text files with blocks of data separated by blank lines. Works well with \n or \r\n line endings.
Contains the TextBlocks
trait which adds the methods as_blocks
, block_parse_lines
and block_parse
to str
and String
.
Install
Run the following command in your project directory:
Or add the following to your Cargo.toml
:
[]
= "0.1.0"
Check the crates.io page for the latest version.
Usage
To parse text into blocks, you need to provide a block delimiter, a line parser and a block parser.
- The block delimiter is a string that separates blocks. The default is a blank line (double newline), but you can use any string.
BlockDelimiter::DoubleLineGeneric
(the default) will use"\r\n\r\n"
if the string contains"\r\n"
newlines, otherwise"\n\n"
.BlockDelimiter::Delimiter(s)
will uses
(aString
) as the delimiter.
- The line parser is any function or closure that takes a
&str
and returns a value of typeT
. The final result will be aVec<Vec<T>>
. You can use theblock_parse_lines
method if you don't need a block parser and only want to parse the lines. - The block parser is any function or closure that takes a
&[T]
and returns a value of typeU
. The final result will be aVec<U>
.
Examples
- Parse a block into a vector of lines
[!IMPORTANT] This will allocate a vector of vectors of
&str
. If you want to avoid these allocations, useblock_parse_lines
orblock_parse
. In that case, A vector will only be allocated for the requested result type.
use *;
let s = "100\n200\n\n300\n400\n\n500\n600";
let block_delimiter = DoubleLineGeneric;
assert_eq!;
assert_eq!;
- Parse a block into a vector of lines, where each line is parsed into a number (u32)
use *;
let s = "100\n200\n\n300\n400\n\n500\n600";
let block_delimiter = DoubleLineGeneric;
let result = s.block_parse_lines;
assert_eq!;
- Parse a block into a vector of lines, where each line is parsed into a number (u32), and then sum the numbers
use *;
let s = "100\n200\n\n300\n400\n\n500\n600";
let block_delimiter = DoubleLineGeneric;
let result = s.block_parse;
assert_eq!;