Skip to content

Commit f17e500

Browse files
committed
doc: add example that uses an alternation
And we make it an interesting example, i.e., one that demonstrates preference order semantics. Closes #610
1 parent da6b1e5 commit f17e500

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/lib.rs

+19
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,25 @@ xy concatenation (x followed by y)
327327
x|y alternation (x or y, prefer x)
328328
</pre>
329329
330+
This example shows how an alternation works, and what it means to prefer a
331+
branch in the alternation over subsequent branches.
332+
333+
```
334+
use regex::Regex;
335+
336+
let haystack = "samwise";
337+
// If 'samwise' comes first in our alternation, then it is
338+
// preferred as a match, even if the regex engine could
339+
// technically detect that 'sam' led to a match earlier.
340+
let re = Regex::new(r"samwise|sam").unwrap();
341+
assert_eq!("samwise", re.find(haystack).unwrap().as_str());
342+
// But if 'sam' comes first, then it will match instead.
343+
// In this case, it is impossible for 'samwise' to match
344+
// because 'sam' is a prefix of it.
345+
let re = Regex::new(r"sam|samwise").unwrap();
346+
assert_eq!("sam", re.find(haystack).unwrap().as_str());
347+
```
348+
330349
## Repetitions
331350
332351
<pre class="rust">

0 commit comments

Comments
 (0)