我想从输入""Name 1" something else"
中提取"Name 1"
,剩余的字符串作为" something else"
。注意转义的"
。
我当前的解决方案是
use nom::bytes::complete::{tag, is_not};
use nom::sequence::pair;
use nom::IResult;
fn parse_between(i: &str) -> IResult<&str, &str> {
let (i, (_o1, o2)) = pair(tag("""), is_not("""))(i)?;
if let Some(res) = i.strip_prefix(""") {
return Ok((res, o2));
}
Ok((i, o2))
}
fn main() {
println!("{:?}", parse_between(""Name 1" something else"));
}
,其中输出为Ok((" something else", "Name 1"))
。
有更好的方法吗?我觉得好像调用strip_prefix
是一个额外的步骤,我不应该做?
Rust Playground link
我相信你是在找delimited
。以下是nom
文档中的一个示例:
use nom::{
IResult,
sequence::delimited,
// see the "streaming/complete" paragraph lower for an explanation of these submodules
character::complete::char,
bytes::complete::is_not
};
fn parens(input: &str) -> IResult<&str, &str> {
delimited(char('('), is_not(")"), char(')'))(input)
}
用它来做你想做的事:
use nom::bytes::complete::is_not;
use nom::character::complete::char;
use nom::sequence::delimited;
use nom::IResult;
fn parse_between(i: &str) -> IResult<&str, &str> {
delimited(char('"'), is_not("""), char('"'))(i)
}
fn main() {
println!("{:?}", parse_between(""Name 1" something else"));
// Ok((" something else", "Name 1"))
}