gpt4 book ai didi

regex - 如何通过 nom 解析匹配的分隔符?

转载 作者:行者123 更新时间:2023-11-29 08:28:23 25 4
gpt4 key购买 nike

我想通过nom库解析四种形式的YMD日期(“20190919”、“2019.09.19”、“2019-09-19”和“2019/09/19”) .

我从 iso8601 开始仅解析“YYYY-MM-DD”形式的解析器。我尝试匹配分隔符并将其重新用于下一次匹配,就像在正则表达式 (\d{4})([.-/]?)(\d{2})\2(\d{2}) 中一样.

原来这段代码有效:

fn parse_ymd(i: &[u8]) -> IResult<&[u8], DateType> {
let (i, y) = year(i)?;

// Match separator if it exist.
let (i, sep) = opt(one_of(".-/"))(i)?;

let (i, m) = month(i)?;

// If first separator was matched then try to find next one.
let (i, _) = if let Some(sep) = sep {
tag(&[sep as u8])(i)?
} else {
// Support the same signature as previous branch.
(i, &[' ' as u8][..])
};

let (i, d) = day(i)?;

Ok((
i,
DateType::YMD {
year: y,
month: m,
day: d,
},
))
}

但显然它看起来很奇怪。

是否有一些 nom 工具可以更合适地做到这一点?

(这个问题关于nom 功能,以及如何正确地做事。不只是关于这个特定的例子。)

最佳答案

您的解决方案足够不错。我真的只能提供一个建议:

fn parse_ymd(i: &[u8]) -> IResult<&[u8], DateType> {
...

// If first separator was matched then try to find next one.
let i = match sep {
Some(sep) => tag(&[sep as u8])(i)?.0,
_ => i,
};

...
}

您可能不熟悉直接访问元组元素的语法。来自 rust book :

In addition to destructuring through pattern matching, we can access a tuple element directly by using a period (.) followed by the index of the value we want to access.

在这种情况下,它可以避免尝试匹配两个 ARM 的签名的尴尬。

关于regex - 如何通过 nom 解析匹配的分隔符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58011745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com