我想解析一个在单引号之间包含ASCII字符的字符串,并且该字符串可以包含连续两个'的转义单引号。
'包含在单引号之间的字符串值->''等等...'
应导致:
包含在单引号之间的字符串值->',依此类推...
use nom::{
bytes::complete::{tag, take_while},
error::{ErrorKind, ParseError},
sequence::delimited,
IResult,
};
fn main() {
let res = string_value::<(&str, ErrorKind)>("'abc''def'");
assert_eq!(res, Ok(("", "abc\'def")));
}
pub fn is_ascii_char(chr: char) -> bool {
chr.is_ascii()
}
fn string_value<'a, E: ParseError<&'a str>>(i: &'a str) -> IResult<&'a str, &'a str, E> {
delimited(tag("'"), take_while(is_ascii_char), tag("'"))(i)
}
如何检测转义引号而不是字符串的结尾?
答案 0 :(得分:1)
这很棘手,但是可以起作用:
//# nom = "5.0.1"
use nom::{
bytes::complete::{escaped_transform, tag},
character::complete::none_of,
combinator::{recognize, map_parser},
multi::{many0, separated_list},
sequence::delimited,
IResult,
};
fn main() {
let (_, res) = parse_quoted("'abc''def'").unwrap();
assert_eq!(res, "abc'def");
let (_, res) = parse_quoted("'xy@$%!z'").unwrap();
assert_eq!(res, "xy@$%!z");
let (_, res) = parse_quoted("'single quotes -> '' and so on...'").unwrap();
assert_eq!(res, "single quotes -> ' and so on...");
}
fn parse_quoted(input: &str) -> IResult<&str, String> {
let seq = recognize(separated_list(tag("''"), many0(none_of("'"))));
let unquote = escaped_transform(none_of("'"), '\'', tag("'"));
let res = delimited(tag("'"), map_parser(seq, unquote), tag("'"))(input)?;
Ok(res)
}
一些解释:
seq
识别在双引号和其他任何东西之间交替的任何序列; unquote
将所有双引号转换为单引号; map_parser
然后将两者结合在一起以产生所需的结果。请注意,由于使用了escaped_transform
组合器,因此解析结果是String
而不是&str
。也就是说,还有额外的分配。