-1

一段时间以来,我一直在尝试为 Nom 找到一个体面的解决方案,以将 slug 识别为alpha1. 所以我可以解析这样的东西

fn parse<'a>(text: &'a str) -> IResult<&'a str, &'a str> {
  delimited(char(':'), slug, char(':'))(text)
}

assert!(
  parse(":hello-world-i-only-accept-alpha-numeric-char-and-dashes:"),
  "hello-world-i-only-accept-alpha-numeric-char-and-dashes"
);

我试过这样的东西,但它似乎不起作用。

fn slug<T, E: ParseError<T>>(input: T) -> IResult<T, T, E>
where
    T: InputTakeAtPosition,
    <T as InputTakeAtPosition>::Item: AsChar + Clone,
{
    input.split_at_position1(
        |item| {
            let c = item.clone().as_char();

            !(item.is_alpha() || c == '-')
        },
        ErrorKind::Char,
    )
}

PS:你知道如何告诉 Nom slug 中的“-”不能在开头也不能在结尾?

4

1 回答 1

1

正是nom::multi::separated_list为了这个。而且由于您希望结果是字符串本身而不是段向量,因此将其与以下内容结合使用即可nom::combinator::recognize

use std::error::Error;
use nom::{
    IResult,
    character::complete::{alphanumeric1, char},
    combinator::recognize,
    multi::separated_list,
    sequence::delimited,
};

fn slug_parse<'a>(text: &'a str) -> IResult<&'a str, &'a str> {
    let slug = separated_list(char('-'), alphanumeric1);
    delimited(char(':'), recognize(slug), char(':'))(text)
}

fn main() -> Result<(), Box<dyn Error>> {
    let (_, res) = slug_parse(":hello-world-i-only-accept-alpha-numeric-char-and-dashes:")?;
    assert_eq!(
      res,
      "hello-world-i-only-accept-alpha-numeric-char-and-dashes"
    );

    Ok(())
}
于 2020-02-01T07:59:39.927 回答