winnow::ascii

Function take_escaped

Source
pub fn take_escaped<Input, Error, Normal, Escapable, NormalOutput, EscapableOutput>(
    normal: Normal,
    control_char: char,
    escapable: Escapable,
) -> impl Parser<Input, <Input as Stream>::Slice, Error>
where Input: StreamIsPartial + Stream + Compare<char>, Normal: Parser<Input, NormalOutput, Error>, Escapable: Parser<Input, EscapableOutput, Error>, Error: ParserError<Input>,
Expand description

Recognize the input slice with escaped characters.

Arguments:

  • normal: unescapeable characters
    • Must not include control
  • control_char: e.g. \ for strings in most languages
  • escape: parse and transform the escaped character

Parsing ends when:

  • alt(normal, control._char) Backtracks
  • normal doesn’t advance the input stream
  • (complete) input stream is exhausted

See also escaped_transform

Warning: If the normal parser passed to take_escaped accepts empty inputs (like alpha0 or digit0), take_escaped will return an error, to prevent going into an infinite loop.

§Example

use winnow::ascii::take_escaped;
use winnow::token::one_of;

fn esc<'i>(input: &mut &'i str) -> ModalResult<&'i str> {
  take_escaped(digit1, '\\', one_of(['"', 'n', '\\'])).parse_next(input)
}

assert_eq!(esc.parse_peek("123;"), Ok((";", "123")));
assert_eq!(esc.parse_peek(r#"12\"34;"#), Ok((";", r#"12\"34"#)));
use winnow::ascii::take_escaped;
use winnow::token::one_of;

fn esc<'i>(input: &mut Partial<&'i str>) -> ModalResult<&'i str> {
  take_escaped(digit1, '\\', one_of(['"', 'n', '\\'])).parse_next(input)
}

assert_eq!(esc.parse_peek(Partial::new("123;")), Ok((Partial::new(";"), "123")));
assert_eq!(esc.parse_peek(Partial::new("12\\\"34;")), Ok((Partial::new(";"), "12\\\"34")));