Skip to content

Commit 40c7985

Browse files
doc: add a doctest to demonstrate a separately-compiled regex set
- explicitly link to and describe the operations that aren't available - reflow text and uncomment use statement
1 parent 9aef5b1 commit 40c7985

File tree

1 file changed

+38
-6
lines changed

1 file changed

+38
-6
lines changed

src/re_set.rs

+38-6
Original file line numberDiff line numberDiff line change
@@ -59,13 +59,45 @@ $(#[$doc_regexset_example])*
5959
/// 1. Does any regex in the set match?
6060
/// 2. If so, which regexes in the set match?
6161
///
62-
/// As with the main `Regex` type, it is cheaper to ask (1) instead of (2)
63-
/// since the matching engines can stop after the first match is found.
62+
/// As with the main [`Regex`][crate::Regex] type, it is cheaper to ask (1)
63+
/// instead of (2) since the matching engines can stop after the first match
64+
/// is found.
6465
///
65-
/// Other features like finding the location of successive matches or their
66-
/// sub-captures aren't supported. If you need this functionality, the
67-
/// recommended approach is to compile each regex in the set independently and
68-
/// selectively match them based on which regexes in the set matched.
66+
/// You cannot directly extract [`Match`][crate::Match] or
67+
/// [`Captures`][crate::Captures] objects from a regex set. If you need these
68+
/// operations, the recommended approach is to compile each pattern in the set
69+
/// independently and scan the exact same input a second time with those
70+
/// independently compiled patterns:
71+
///
72+
/// ```rust
73+
///
74+
/// use regex::{Regex, RegexSet};
75+
/// let patterns = ["foo", "bar"];
76+
/// // Both patterns will match different ranges of this string.
77+
/// let text = "barfoo";
78+
///
79+
/// // Compile a set matching any of our patterns.
80+
/// let set = RegexSet::new(&patterns).unwrap();
81+
/// // Compile each pattern independently.
82+
/// let regexes: Vec<_> = patterns.iter()
83+
/// .map(|pat| Regex::new(pat).unwrap())
84+
/// .collect();
85+
///
86+
/// // Match against the whole set first and identify the individual
87+
/// // matching patterns.
88+
/// let matches: Vec<&str> = set.matches(text).into_iter()
89+
/// // Dereference the match index to get the corresponding
90+
/// // compiled pattern.
91+
/// .map(|match_idx| &regexes[match_idx])
92+
/// // To get match locations or any other info, we then have to search
93+
/// // the exact same text again, using our separately-compiled pattern.
94+
/// .map(|pat| pat.find(text).unwrap().as_str())
95+
/// .collect();
96+
///
97+
/// // Matches arrive in the order the constituent patterns were declared,
98+
/// // not the order they appear in the input.
99+
/// assert_eq!(vec!["foo", "bar"], matches);
100+
/// ```
69101
///
70102
/// # Performance
71103
///

0 commit comments

Comments
 (0)