From 20aef4adbe1bc75b003def4859bea7be18b7c0ba Mon Sep 17 00:00:00 2001 From: Andrew Gallant Date: Mon, 6 Mar 2023 11:06:50 -0500 Subject: [PATCH] doc: add example that uses an alternation And we make it an interesting example, i.e., one that demonstrates preference order semantics. Closes #610 --- src/lib.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 5f92bc85a..97d304787 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -327,6 +327,25 @@ xy concatenation (x followed by y) x|y alternation (x or y, prefer x) +This example shows how an alternation works, and what it means to prefer a +branch in the alternation over subsequent branches. + +``` +use regex::Regex; + +let haystack = "samwise"; +// If 'samwise' comes first in our alternation, then it is +// preferred as a match, even if the regex engine could +// technically detect that 'sam' led to a match earlier. +let re = Regex::new(r"samwise|sam").unwrap(); +assert_eq!("samwise", re.find(haystack).unwrap().as_str()); +// But if 'sam' comes first, then it will match instead. +// In this case, it is impossible for 'samwise' to match +// because 'sam' is a prefix of it. +let re = Regex::new(r"sam|samwise").unwrap(); +assert_eq!("sam", re.find(haystack).unwrap().as_str()); +``` + ## Repetitions