Search code examples
rustnom

Catch string between tags with nom delimited


I'm trying to learn to use nom (5.0.1) and want to get the string between two tags:

use nom::{
    bytes::complete::{tag_no_case, take_while},
    character::{is_alphanumeric},
    error::{ParseError},
    sequence::{delimited},
    IResult,
};

fn root<'a, E: ParseError<&'a str>>(i: &'a str) -> IResult<&'a str, &str, E> {
    delimited(
        tag_no_case("START;"),
        take_while(is_alphanumeric),
        tag_no_case("END;"),
    )(i)
}

But this gives me the error

error[E0271]: type mismatch resolving `<&str as nom::InputTakeAtPosition>::Item == u8`
   --> src/main.rs:128:9
    |
128 |         take_while(is_alphanumeric),
    |         ^^^^^^^^^^^ expected char, found u8

What have I done wrong here? I'm fairly new to Rust and a total beginner with nom so I'm expecting it to be something really obvious in the end :)


Solution

  • The is_alphanumeric from nom expects a parameter of type u8, but you give it a char. Use is_alphanumeric from std instead:

    fn root<'a, E: ParseError<&'a str>>(i: &'a str) -> IResult<&'a str, &str, E> {
        delimited(
            tag_no_case("START;"),
            take_while(char::is_alphanumeric),
            tag_no_case("END;"),
        )(i)
    }