pub fn regex<'h, Input, Re, Error>(
re: Re,
) -> RegexParser<'h, Input, Re::Output, Error>where
Input: StreamIsPartial + Stream + Offset + Clone,
Re: RegexPattern,
Re::Output: Regex<Haystack<'h> = <Input as Stream>::Slice>,
Re::Error: Debug,
Error: ParserError<Input> + 'static,
Expand description
Creates a parser that matches input using a regular expression.
This parser takes a regular expression pattern (implementing RegexPattern
)
and returns a parser that attempts to match from the beginning of the input.
If the regular expression does not match at position 0, the parser fails.
Internally, this uses a precompiled Regex
from the [regex
] crate and supports
both complete and partial input modes via the StreamIsPartial
trait.
§Panics
Panics if the regex pattern fails to compile.
§Example
use winnow::prelude::*;
use winnow_regex::regex;
fn digits<'i>(s: &mut &'i str) -> ModalResult<&'i str> {
regex(r"^\d+").parse_next(s)
}
assert_eq!(digits.parse_peek("42abc"), Ok(("abc", "42")));
assert!(digits.parse_peek("abc42").is_err());
// Example with precompiled regex
fn word<'i>(s: &mut &'i str) -> ModalResult<&'i str> {
let re = regex::Regex::new(r"^\w+").unwrap();
regex(re).parse_next(s)
}
assert_eq!(word.parse_peek("hello world"), Ok((" world", "hello")));
assert!(word.parse_peek("!hello").is_err());