pub fn escaped_transform<I, Error, F, G, Output>(
    normal: F,
    control_char: char,
    transform: G
) -> impl FnMut(I) -> IResult<I, Output, Error>where
    I: StreamIsPartial + Stream + Offset,
    <I as Stream>::Token: AsChar,
    Output: Accumulate<<I as Stream>::Slice>,
    F: Parser<I, <I as Stream>::Slice, Error>,
    G: Parser<I, <I as Stream>::Slice, Error>,
    Error: ParseError<I>,
Available on crate feature alloc only.
Expand description

Matches a byte string with escaped characters.

  • The first argument matches the normal characters (it must not match the control character)
  • The second argument is the control character (like \ in most languages)
  • The third argument matches the escaped characters and transforms them

As an example, the chain abc\tdef could be abc def (it also consumes the control character)

Example

use winnow::bytes::tag;
use winnow::character::escaped_transform;
use winnow::character::alpha1;
use winnow::branch::alt;
use winnow::combinator::value;

fn parser(input: &str) -> IResult<&str, String> {
  escaped_transform(
    alpha1,
    '\\',
    alt((
      tag("\\").value("\\"),
      tag("\"").value("\""),
      tag("n").value("\n"),
    ))
  )(input)
}

assert_eq!(parser("ab\\\"cd"), Ok(("", String::from("ab\"cd"))));
assert_eq!(parser("ab\\ncd"), Ok(("", String::from("ab\ncd"))));
use winnow::bytes::tag;
use winnow::character::escaped_transform;
use winnow::character::alpha1;
use winnow::branch::alt;
use winnow::combinator::value;

fn parser(input: Partial<&str>) -> IResult<Partial<&str>, String> {
  escaped_transform(
    alpha1,
    '\\',
    alt((
      tag("\\").value("\\"),
      tag("\"").value("\""),
      tag("n").value("\n"),
    ))
  )(input)
}

assert_eq!(parser(Partial::new("ab\\\"cd\"")), Ok((Partial::new("\""), String::from("ab\"cd"))));