I'm trying to parse the following alternate strings with nom5.0
"A-Za-z0-9"
or
"A-Z|a-z|0-9"
I've tried the following but to no avail
pub enum Node {
Range(Vec<u8>),
}
fn compound_range(input: &[u8]) -> IResult<&[u8], Node> {
map(
separated_list(
alt((tag("|"), tag(""))),
tuple((take(1usize), tag("-"), take(1usize))),
),
|v: Vec<(&[u8], _, &[u8])>| {
Node::Range(
v.iter()
.map(|(s, _, e)| (s[0]..=e[0]).collect::<Vec<_>>())
.flatten()
.collect(),
)
},
)(input)
}
Version 2.
fn compound_range(input: &[u8]) -> IResult<&[u8], Node> {
alt((
map(
separated_list(tag("|"), tuple((take(1usize), tag("-"), take(1usize)))),
|v: Vec<(&[u8], _, &[u8])>| {
Node::Range(
v.iter()
.map(|(s, _, e)| (s[0]..=e[0]).collect::<Vec<_>>())
.flatten()
.collect(),
)
},
),
map(
many1(tuple((take(1usize), tag("-"), take(1usize)))),
|v: Vec<(&[u8], _, &[u8])>| {
Node::Range(
v.iter()
.map(|(s, _, e)| (s[0]..=e[0]).collect::<Vec<_>>())
.flatten()
.collect(),
)
},
),
))(input)
}
#[test]
fn parse_compound() {
println!("{:?}", compound_range(b"A-Za-z0-9"));
println!("{:?}", compound_range(b"A-Z|a-z|0-9"));
}
I can either get the first or the second one to parse but never both. Is there a way to express this?