1个不稳定版本
0.1.1 | 2019年7月29日 |
---|
#17 in #special
5KB
nom-both
nom的扩展,提供特殊的both_
解析器。
要求
nom必须为5.0.0或更高版本。nom-both只能应用于函数式解析器。
使用
[dependencies]
nom-both = "0.1.1"
示例
nom-both提供both_opt
和both_alt
解析器。both_opt
表示解析器尝试同时进行参数解析器和跳过解析。both_alt
表示解析器尝试第一个参数解析器和第二个参数解析器。
use nom::branch::*;
use nom::bytes::complete::*;
use nom::IResult;
use nom_both::both_parser;
#[both_parser]
pub fn both_opt_parser(s: &str) -> IResult<&str, Option<&str>> {
let (s, _) = tag("1")(s)?;
let (s, x) = both_opt(tag("2"))(s)?;
let (s, _) = tag("2")(s)?;
let (s, _) = tag("3")(s)?;
Ok((s, x))
}
#[both_parser]
pub fn both_alt_parser(s: &str) -> IResult<&str, &str> {
let (s, _) = tag("1")(s)?;
let (s, x) = both_alt(tag("22"), tag("2"))(s)?;
let (s, _) = tag("2")(s)?;
let (s, _) = tag("3")(s)?;
Ok((s, x))
}
#[test]
fn test() {
let ret = both_opt_parser("123");
assert_eq!("None", format!("{:?}", ret.unwrap().1));
let ret = both_alt_parser("1223");
assert_eq!("\"2\"", format!("{:?}", ret.unwrap().1));
}
both_opt_parser
的展开如下
pub fn both_opt_parser(s: &str) -> IResult<&str, Option<&str>> {
alt((
{ |s| {
let (s, _) = tag("1")(s)?;
let (s, x) = nom_both::some(tag("2"))(s)?;
let (s, _) = tag("2")(s)?;
let (s, _) = tag("3")(s)?;
Ok((s, x))
} },
{ |s| {
let (s, _) = tag("1")(s)?;
let (s, x) = nom_both::none(tag("2"))(s)?;
let (s, _) = tag("2")(s)?;
let (s, _) = tag("3")(s)?;
Ok((s, x))
} },
))(s)
}
both_alt_parser
的展开如下
pub fn both_opt_parser(s: &str) -> IResult<&str, Option<&str>> {
alt((
{ |s| {
let (s, _) = tag("1")(s)?;
let (s, x) = nom_both::alt_left(tag("22"), tag("2"))(s)?;
let (s, _) = tag("2")(s)?;
let (s, _) = tag("3")(s)?;
Ok((s, x))
} },
{ |s| {
let (s, _) = tag("1")(s)?;
let (s, x) = nom_both::alt_right(tag("22"), tag("2"))(s)?;
let (s, _) = tag("2")(s)?;
let (s, _) = tag("3")(s)?;
Ok((s, x))
} },
))(s)
}
许可证
以下任一许可证下授权:
- Apache许可证2.0版,(LICENSE-APACHE 或 https://apache.ac.cn/licenses/LICENSE-2.0)
- MIT许可证 (LICENSE-MIT 或 http://opensource.org/licenses/MIT)
任选其一。
贡献
除非您明确声明,否则任何提交给工作以包含在内的有意贡献,根据Apache-2.0许可证定义,应双授权如上所述,不附加任何额外条款或条件。
依赖项
~3MB
~64K SLoC