/rust/registry/src/index.crates.io-6f17d22bba15001f/regex-1.5.6/src/re_unicode.rs
Line | Count | Source (jump to first uncovered line) |
1 | | use std::borrow::Cow; |
2 | | use std::collections::HashMap; |
3 | | use std::fmt; |
4 | | use std::iter::FusedIterator; |
5 | | use std::ops::{Index, Range}; |
6 | | use std::str::FromStr; |
7 | | use std::sync::Arc; |
8 | | |
9 | | use crate::find_byte::find_byte; |
10 | | |
11 | | use crate::error::Error; |
12 | | use crate::exec::{Exec, ExecNoSyncStr}; |
13 | | use crate::expand::expand_str; |
14 | | use crate::re_builder::unicode::RegexBuilder; |
15 | | use crate::re_trait::{self, RegularExpression, SubCapturesPosIter}; |
16 | | |
17 | | /// Escapes all regular expression meta characters in `text`. |
18 | | /// |
19 | | /// The string returned may be safely used as a literal in a regular |
20 | | /// expression. |
21 | 0 | pub fn escape(text: &str) -> String { |
22 | 0 | regex_syntax::escape(text) |
23 | 0 | } Unexecuted instantiation: regex::re_unicode::escape Unexecuted instantiation: regex::re_unicode::escape |
24 | | |
25 | | /// Match represents a single match of a regex in a haystack. |
26 | | /// |
27 | | /// The lifetime parameter `'t` refers to the lifetime of the matched text. |
28 | | #[derive(Copy, Clone, Debug, Eq, PartialEq)] |
29 | | pub struct Match<'t> { |
30 | | text: &'t str, |
31 | | start: usize, |
32 | | end: usize, |
33 | | } |
34 | | |
35 | | impl<'t> Match<'t> { |
36 | | /// Returns the starting byte offset of the match in the haystack. |
37 | | #[inline] |
38 | 0 | pub fn start(&self) -> usize { |
39 | 0 | self.start |
40 | 0 | } Unexecuted instantiation: <regex::re_unicode::Match>::start Unexecuted instantiation: <regex::re_unicode::Match>::start |
41 | | |
42 | | /// Returns the ending byte offset of the match in the haystack. |
43 | | #[inline] |
44 | 0 | pub fn end(&self) -> usize { |
45 | 0 | self.end |
46 | 0 | } Unexecuted instantiation: <regex::re_unicode::Match>::end Unexecuted instantiation: <regex::re_unicode::Match>::end |
47 | | |
48 | | /// Returns the range over the starting and ending byte offsets of the |
49 | | /// match in the haystack. |
50 | | #[inline] |
51 | 51.5k | pub fn range(&self) -> Range<usize> { |
52 | 51.5k | self.start..self.end |
53 | 51.5k | } <regex::re_unicode::Match>::range Line | Count | Source | 51 | 48.4k | pub fn range(&self) -> Range<usize> { | 52 | 48.4k | self.start..self.end | 53 | 48.4k | } |
<regex::re_unicode::Match>::range Line | Count | Source | 51 | 3.12k | pub fn range(&self) -> Range<usize> { | 52 | 3.12k | self.start..self.end | 53 | 3.12k | } |
|
54 | | |
55 | | /// Returns the matched text. |
56 | | #[inline] |
57 | 51.5k | pub fn as_str(&self) -> &'t str { |
58 | 51.5k | &self.text[self.range()] |
59 | 51.5k | } <regex::re_unicode::Match>::as_str Line | Count | Source | 57 | 48.4k | pub fn as_str(&self) -> &'t str { | 58 | 48.4k | &self.text[self.range()] | 59 | 48.4k | } |
<regex::re_unicode::Match>::as_str Line | Count | Source | 57 | 3.12k | pub fn as_str(&self) -> &'t str { | 58 | 3.12k | &self.text[self.range()] | 59 | 3.12k | } |
|
60 | | |
61 | | /// Creates a new match from the given haystack and byte offsets. |
62 | | #[inline] |
63 | 82.0k | fn new(haystack: &'t str, start: usize, end: usize) -> Match<'t> { |
64 | 82.0k | Match { text: haystack, start: start, end: end } |
65 | 82.0k | } <regex::re_unicode::Match>::new Line | Count | Source | 63 | 77.3k | fn new(haystack: &'t str, start: usize, end: usize) -> Match<'t> { | 64 | 77.3k | Match { text: haystack, start: start, end: end } | 65 | 77.3k | } |
<regex::re_unicode::Match>::new Line | Count | Source | 63 | 4.62k | fn new(haystack: &'t str, start: usize, end: usize) -> Match<'t> { | 64 | 4.62k | Match { text: haystack, start: start, end: end } | 65 | 4.62k | } |
|
66 | | } |
67 | | |
68 | | impl<'t> From<Match<'t>> for &'t str { |
69 | 0 | fn from(m: Match<'t>) -> &'t str { |
70 | 0 | m.as_str() |
71 | 0 | } Unexecuted instantiation: <&str as core::convert::From<regex::re_unicode::Match>>::from Unexecuted instantiation: <&str as core::convert::From<regex::re_unicode::Match>>::from |
72 | | } |
73 | | |
74 | | impl<'t> From<Match<'t>> for Range<usize> { |
75 | 0 | fn from(m: Match<'t>) -> Range<usize> { |
76 | 0 | m.range() |
77 | 0 | } Unexecuted instantiation: <core::ops::range::Range<usize> as core::convert::From<regex::re_unicode::Match>>::from Unexecuted instantiation: <core::ops::range::Range<usize> as core::convert::From<regex::re_unicode::Match>>::from |
78 | | } |
79 | | |
80 | | /// A compiled regular expression for matching Unicode strings. |
81 | | /// |
82 | | /// It is represented as either a sequence of bytecode instructions (dynamic) |
83 | | /// or as a specialized Rust function (native). It can be used to search, split |
84 | | /// or replace text. All searching is done with an implicit `.*?` at the |
85 | | /// beginning and end of an expression. To force an expression to match the |
86 | | /// whole string (or a prefix or a suffix), you must use an anchor like `^` or |
87 | | /// `$` (or `\A` and `\z`). |
88 | | /// |
89 | | /// While this crate will handle Unicode strings (whether in the regular |
90 | | /// expression or in the search text), all positions returned are **byte |
91 | | /// indices**. Every byte index is guaranteed to be at a Unicode code point |
92 | | /// boundary. |
93 | | /// |
94 | | /// The lifetimes `'r` and `'t` in this crate correspond to the lifetime of a |
95 | | /// compiled regular expression and text to search, respectively. |
96 | | /// |
97 | | /// The only methods that allocate new strings are the string replacement |
98 | | /// methods. All other methods (searching and splitting) return borrowed |
99 | | /// pointers into the string given. |
100 | | /// |
101 | | /// # Examples |
102 | | /// |
103 | | /// Find the location of a US phone number: |
104 | | /// |
105 | | /// ```rust |
106 | | /// # use regex::Regex; |
107 | | /// let re = Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}").unwrap(); |
108 | | /// let mat = re.find("phone: 111-222-3333").unwrap(); |
109 | | /// assert_eq!((mat.start(), mat.end()), (7, 19)); |
110 | | /// ``` |
111 | | /// |
112 | | /// # Using the `std::str::pattern` methods with `Regex` |
113 | | /// |
114 | | /// > **Note**: This section requires that this crate is compiled with the |
115 | | /// > `pattern` Cargo feature enabled, which **requires nightly Rust**. |
116 | | /// |
117 | | /// Since `Regex` implements `Pattern`, you can use regexes with methods |
118 | | /// defined on `&str`. For example, `is_match`, `find`, `find_iter` |
119 | | /// and `split` can be replaced with `str::contains`, `str::find`, |
120 | | /// `str::match_indices` and `str::split`. |
121 | | /// |
122 | | /// Here are some examples: |
123 | | /// |
124 | | /// ```rust,ignore |
125 | | /// # use regex::Regex; |
126 | | /// let re = Regex::new(r"\d+").unwrap(); |
127 | | /// let haystack = "a111b222c"; |
128 | | /// |
129 | | /// assert!(haystack.contains(&re)); |
130 | | /// assert_eq!(haystack.find(&re), Some(1)); |
131 | | /// assert_eq!(haystack.match_indices(&re).collect::<Vec<_>>(), |
132 | | /// vec![(1, 4), (5, 8)]); |
133 | | /// assert_eq!(haystack.split(&re).collect::<Vec<_>>(), vec!["a", "b", "c"]); |
134 | | /// ``` |
135 | | #[derive(Clone)] |
136 | | pub struct Regex(Exec); |
137 | | |
138 | | impl fmt::Display for Regex { |
139 | | /// Shows the original regular expression. |
140 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
141 | 0 | write!(f, "{}", self.as_str()) |
142 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex as core::fmt::Display>::fmt Unexecuted instantiation: <regex::re_unicode::Regex as core::fmt::Display>::fmt |
143 | | } |
144 | | |
145 | | impl fmt::Debug for Regex { |
146 | | /// Shows the original regular expression. |
147 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
148 | 0 | fmt::Display::fmt(self, f) |
149 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex as core::fmt::Debug>::fmt Unexecuted instantiation: <regex::re_unicode::Regex as core::fmt::Debug>::fmt |
150 | | } |
151 | | |
152 | | #[doc(hidden)] |
153 | | impl From<Exec> for Regex { |
154 | 15 | fn from(exec: Exec) -> Regex { |
155 | 15 | Regex(exec) |
156 | 15 | } <regex::re_unicode::Regex as core::convert::From<regex::exec::Exec>>::from Line | Count | Source | 154 | 9 | fn from(exec: Exec) -> Regex { | 155 | 9 | Regex(exec) | 156 | 9 | } |
<regex::re_unicode::Regex as core::convert::From<regex::exec::Exec>>::from Line | Count | Source | 154 | 6 | fn from(exec: Exec) -> Regex { | 155 | 6 | Regex(exec) | 156 | 6 | } |
|
157 | | } |
158 | | |
159 | | impl FromStr for Regex { |
160 | | type Err = Error; |
161 | | |
162 | | /// Attempts to parse a string into a regular expression |
163 | 0 | fn from_str(s: &str) -> Result<Regex, Error> { |
164 | 0 | Regex::new(s) |
165 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex as core::str::traits::FromStr>::from_str Unexecuted instantiation: <regex::re_unicode::Regex as core::str::traits::FromStr>::from_str |
166 | | } |
167 | | |
168 | | /// Core regular expression methods. |
169 | | impl Regex { |
170 | | /// Compiles a regular expression. Once compiled, it can be used repeatedly |
171 | | /// to search, split or replace text in a string. |
172 | | /// |
173 | | /// If an invalid expression is given, then an error is returned. |
174 | 15 | pub fn new(re: &str) -> Result<Regex, Error> { |
175 | 15 | RegexBuilder::new(re).build() |
176 | 15 | } <regex::re_unicode::Regex>::new Line | Count | Source | 174 | 9 | pub fn new(re: &str) -> Result<Regex, Error> { | 175 | 9 | RegexBuilder::new(re).build() | 176 | 9 | } |
<regex::re_unicode::Regex>::new Line | Count | Source | 174 | 6 | pub fn new(re: &str) -> Result<Regex, Error> { | 175 | 6 | RegexBuilder::new(re).build() | 176 | 6 | } |
|
177 | | |
178 | | /// Returns true if and only if there is a match for the regex in the |
179 | | /// string given. |
180 | | /// |
181 | | /// It is recommended to use this method if all you need to do is test |
182 | | /// a match, since the underlying matching engine may be able to do less |
183 | | /// work. |
184 | | /// |
185 | | /// # Example |
186 | | /// |
187 | | /// Test if some text contains at least one word with exactly 13 |
188 | | /// Unicode word characters: |
189 | | /// |
190 | | /// ```rust |
191 | | /// # use regex::Regex; |
192 | | /// # fn main() { |
193 | | /// let text = "I categorically deny having triskaidekaphobia."; |
194 | | /// assert!(Regex::new(r"\b\w{13}\b").unwrap().is_match(text)); |
195 | | /// # } |
196 | | /// ``` |
197 | 0 | pub fn is_match(&self, text: &str) -> bool { |
198 | 0 | self.is_match_at(text, 0) |
199 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::is_match Unexecuted instantiation: <regex::re_unicode::Regex>::is_match |
200 | | |
201 | | /// Returns the start and end byte range of the leftmost-first match in |
202 | | /// `text`. If no match exists, then `None` is returned. |
203 | | /// |
204 | | /// Note that this should only be used if you want to discover the position |
205 | | /// of the match. Testing the existence of a match is faster if you use |
206 | | /// `is_match`. |
207 | | /// |
208 | | /// # Example |
209 | | /// |
210 | | /// Find the start and end location of the first word with exactly 13 |
211 | | /// Unicode word characters: |
212 | | /// |
213 | | /// ```rust |
214 | | /// # use regex::Regex; |
215 | | /// # fn main() { |
216 | | /// let text = "I categorically deny having triskaidekaphobia."; |
217 | | /// let mat = Regex::new(r"\b\w{13}\b").unwrap().find(text).unwrap(); |
218 | | /// assert_eq!(mat.start(), 2); |
219 | | /// assert_eq!(mat.end(), 15); |
220 | | /// # } |
221 | | /// ``` |
222 | 0 | pub fn find<'t>(&self, text: &'t str) -> Option<Match<'t>> { |
223 | 0 | self.find_at(text, 0) |
224 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::find Unexecuted instantiation: <regex::re_unicode::Regex>::find |
225 | | |
226 | | /// Returns an iterator for each successive non-overlapping match in |
227 | | /// `text`, returning the start and end byte indices with respect to |
228 | | /// `text`. |
229 | | /// |
230 | | /// # Example |
231 | | /// |
232 | | /// Find the start and end location of every word with exactly 13 Unicode |
233 | | /// word characters: |
234 | | /// |
235 | | /// ```rust |
236 | | /// # use regex::Regex; |
237 | | /// # fn main() { |
238 | | /// let text = "Retroactively relinquishing remunerations is reprehensible."; |
239 | | /// for mat in Regex::new(r"\b\w{13}\b").unwrap().find_iter(text) { |
240 | | /// println!("{:?}", mat); |
241 | | /// } |
242 | | /// # } |
243 | | /// ``` |
244 | 0 | pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> Matches<'r, 't> { |
245 | 0 | Matches(self.0.searcher_str().find_iter(text)) |
246 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::find_iter Unexecuted instantiation: <regex::re_unicode::Regex>::find_iter |
247 | | |
248 | | /// Returns the capture groups corresponding to the leftmost-first |
249 | | /// match in `text`. Capture group `0` always corresponds to the entire |
250 | | /// match. If no match is found, then `None` is returned. |
251 | | /// |
252 | | /// You should only use `captures` if you need access to the location of |
253 | | /// capturing group matches. Otherwise, `find` is faster for discovering |
254 | | /// the location of the overall match. |
255 | | /// |
256 | | /// # Examples |
257 | | /// |
258 | | /// Say you have some text with movie names and their release years, |
259 | | /// like "'Citizen Kane' (1941)". It'd be nice if we could search for text |
260 | | /// looking like that, while also extracting the movie name and its release |
261 | | /// year separately. |
262 | | /// |
263 | | /// ```rust |
264 | | /// # use regex::Regex; |
265 | | /// # fn main() { |
266 | | /// let re = Regex::new(r"'([^']+)'\s+\((\d{4})\)").unwrap(); |
267 | | /// let text = "Not my favorite movie: 'Citizen Kane' (1941)."; |
268 | | /// let caps = re.captures(text).unwrap(); |
269 | | /// assert_eq!(caps.get(1).unwrap().as_str(), "Citizen Kane"); |
270 | | /// assert_eq!(caps.get(2).unwrap().as_str(), "1941"); |
271 | | /// assert_eq!(caps.get(0).unwrap().as_str(), "'Citizen Kane' (1941)"); |
272 | | /// // You can also access the groups by index using the Index notation. |
273 | | /// // Note that this will panic on an invalid index. |
274 | | /// assert_eq!(&caps[1], "Citizen Kane"); |
275 | | /// assert_eq!(&caps[2], "1941"); |
276 | | /// assert_eq!(&caps[0], "'Citizen Kane' (1941)"); |
277 | | /// # } |
278 | | /// ``` |
279 | | /// |
280 | | /// Note that the full match is at capture group `0`. Each subsequent |
281 | | /// capture group is indexed by the order of its opening `(`. |
282 | | /// |
283 | | /// We can make this example a bit clearer by using *named* capture groups: |
284 | | /// |
285 | | /// ```rust |
286 | | /// # use regex::Regex; |
287 | | /// # fn main() { |
288 | | /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)") |
289 | | /// .unwrap(); |
290 | | /// let text = "Not my favorite movie: 'Citizen Kane' (1941)."; |
291 | | /// let caps = re.captures(text).unwrap(); |
292 | | /// assert_eq!(caps.name("title").unwrap().as_str(), "Citizen Kane"); |
293 | | /// assert_eq!(caps.name("year").unwrap().as_str(), "1941"); |
294 | | /// assert_eq!(caps.get(0).unwrap().as_str(), "'Citizen Kane' (1941)"); |
295 | | /// // You can also access the groups by name using the Index notation. |
296 | | /// // Note that this will panic on an invalid group name. |
297 | | /// assert_eq!(&caps["title"], "Citizen Kane"); |
298 | | /// assert_eq!(&caps["year"], "1941"); |
299 | | /// assert_eq!(&caps[0], "'Citizen Kane' (1941)"); |
300 | | /// |
301 | | /// # } |
302 | | /// ``` |
303 | | /// |
304 | | /// Here we name the capture groups, which we can access with the `name` |
305 | | /// method or the `Index` notation with a `&str`. Note that the named |
306 | | /// capture groups are still accessible with `get` or the `Index` notation |
307 | | /// with a `usize`. |
308 | | /// |
309 | | /// The `0`th capture group is always unnamed, so it must always be |
310 | | /// accessed with `get(0)` or `[0]`. |
311 | 78.7k | pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> { |
312 | 78.7k | let mut locs = self.capture_locations(); |
313 | 78.7k | self.captures_read_at(&mut locs, text, 0).map(move |_| Captures { |
314 | 30.4k | text: text, |
315 | 30.4k | locs: locs.0, |
316 | 30.4k | named_groups: self.0.capture_name_idx().clone(), |
317 | 78.7k | }) <regex::re_unicode::Regex>::captures::{closure#0} Line | Count | Source | 313 | 28.9k | self.captures_read_at(&mut locs, text, 0).map(move |_| Captures { | 314 | 28.9k | text: text, | 315 | 28.9k | locs: locs.0, | 316 | 28.9k | named_groups: self.0.capture_name_idx().clone(), | 317 | 28.9k | }) |
<regex::re_unicode::Regex>::captures::{closure#0} Line | Count | Source | 313 | 1.50k | self.captures_read_at(&mut locs, text, 0).map(move |_| Captures { | 314 | 1.50k | text: text, | 315 | 1.50k | locs: locs.0, | 316 | 1.50k | named_groups: self.0.capture_name_idx().clone(), | 317 | 1.50k | }) |
|
318 | 78.7k | } <regex::re_unicode::Regex>::captures Line | Count | Source | 311 | 75.5k | pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> { | 312 | 75.5k | let mut locs = self.capture_locations(); | 313 | 75.5k | self.captures_read_at(&mut locs, text, 0).map(move |_| Captures { | 314 | | text: text, | 315 | | locs: locs.0, | 316 | | named_groups: self.0.capture_name_idx().clone(), | 317 | 75.5k | }) | 318 | 75.5k | } |
<regex::re_unicode::Regex>::captures Line | Count | Source | 311 | 3.15k | pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> { | 312 | 3.15k | let mut locs = self.capture_locations(); | 313 | 3.15k | self.captures_read_at(&mut locs, text, 0).map(move |_| Captures { | 314 | | text: text, | 315 | | locs: locs.0, | 316 | | named_groups: self.0.capture_name_idx().clone(), | 317 | 3.15k | }) | 318 | 3.15k | } |
|
319 | | |
320 | | /// Returns an iterator over all the non-overlapping capture groups matched |
321 | | /// in `text`. This is operationally the same as `find_iter`, except it |
322 | | /// yields information about capturing group matches. |
323 | | /// |
324 | | /// # Example |
325 | | /// |
326 | | /// We can use this to find all movie titles and their release years in |
327 | | /// some text, where the movie is formatted like "'Title' (xxxx)": |
328 | | /// |
329 | | /// ```rust |
330 | | /// # use regex::Regex; |
331 | | /// # fn main() { |
332 | | /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)") |
333 | | /// .unwrap(); |
334 | | /// let text = "'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931)."; |
335 | | /// for caps in re.captures_iter(text) { |
336 | | /// println!("Movie: {:?}, Released: {:?}", |
337 | | /// &caps["title"], &caps["year"]); |
338 | | /// } |
339 | | /// // Output: |
340 | | /// // Movie: Citizen Kane, Released: 1941 |
341 | | /// // Movie: The Wizard of Oz, Released: 1939 |
342 | | /// // Movie: M, Released: 1931 |
343 | | /// # } |
344 | | /// ``` |
345 | 0 | pub fn captures_iter<'r, 't>( |
346 | 0 | &'r self, |
347 | 0 | text: &'t str, |
348 | 0 | ) -> CaptureMatches<'r, 't> { |
349 | 0 | CaptureMatches(self.0.searcher_str().captures_iter(text)) |
350 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::captures_iter Unexecuted instantiation: <regex::re_unicode::Regex>::captures_iter |
351 | | |
352 | | /// Returns an iterator of substrings of `text` delimited by a match of the |
353 | | /// regular expression. Namely, each element of the iterator corresponds to |
354 | | /// text that *isn't* matched by the regular expression. |
355 | | /// |
356 | | /// This method will *not* copy the text given. |
357 | | /// |
358 | | /// # Example |
359 | | /// |
360 | | /// To split a string delimited by arbitrary amounts of spaces or tabs: |
361 | | /// |
362 | | /// ```rust |
363 | | /// # use regex::Regex; |
364 | | /// # fn main() { |
365 | | /// let re = Regex::new(r"[ \t]+").unwrap(); |
366 | | /// let fields: Vec<&str> = re.split("a b \t c\td e").collect(); |
367 | | /// assert_eq!(fields, vec!["a", "b", "c", "d", "e"]); |
368 | | /// # } |
369 | | /// ``` |
370 | 0 | pub fn split<'r, 't>(&'r self, text: &'t str) -> Split<'r, 't> { |
371 | 0 | Split { finder: self.find_iter(text), last: 0 } |
372 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::split Unexecuted instantiation: <regex::re_unicode::Regex>::split |
373 | | |
374 | | /// Returns an iterator of at most `limit` substrings of `text` delimited |
375 | | /// by a match of the regular expression. (A `limit` of `0` will return no |
376 | | /// substrings.) Namely, each element of the iterator corresponds to text |
377 | | /// that *isn't* matched by the regular expression. The remainder of the |
378 | | /// string that is not split will be the last element in the iterator. |
379 | | /// |
380 | | /// This method will *not* copy the text given. |
381 | | /// |
382 | | /// # Example |
383 | | /// |
384 | | /// Get the first two words in some text: |
385 | | /// |
386 | | /// ```rust |
387 | | /// # use regex::Regex; |
388 | | /// # fn main() { |
389 | | /// let re = Regex::new(r"\W+").unwrap(); |
390 | | /// let fields: Vec<&str> = re.splitn("Hey! How are you?", 3).collect(); |
391 | | /// assert_eq!(fields, vec!("Hey", "How", "are you?")); |
392 | | /// # } |
393 | | /// ``` |
394 | 0 | pub fn splitn<'r, 't>( |
395 | 0 | &'r self, |
396 | 0 | text: &'t str, |
397 | 0 | limit: usize, |
398 | 0 | ) -> SplitN<'r, 't> { |
399 | 0 | SplitN { splits: self.split(text), n: limit } |
400 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::splitn Unexecuted instantiation: <regex::re_unicode::Regex>::splitn |
401 | | |
402 | | /// Replaces the leftmost-first match with the replacement provided. |
403 | | /// The replacement can be a regular string (where `$N` and `$name` are |
404 | | /// expanded to match capture groups) or a function that takes the matches' |
405 | | /// `Captures` and returns the replaced string. |
406 | | /// |
407 | | /// If no match is found, then a copy of the string is returned unchanged. |
408 | | /// |
409 | | /// # Replacement string syntax |
410 | | /// |
411 | | /// All instances of `$name` in the replacement text is replaced with the |
412 | | /// corresponding capture group `name`. |
413 | | /// |
414 | | /// `name` may be an integer corresponding to the index of the |
415 | | /// capture group (counted by order of opening parenthesis where `0` is the |
416 | | /// entire match) or it can be a name (consisting of letters, digits or |
417 | | /// underscores) corresponding to a named capture group. |
418 | | /// |
419 | | /// If `name` isn't a valid capture group (whether the name doesn't exist |
420 | | /// or isn't a valid index), then it is replaced with the empty string. |
421 | | /// |
422 | | /// The longest possible name is used. e.g., `$1a` looks up the capture |
423 | | /// group named `1a` and not the capture group at index `1`. To exert more |
424 | | /// precise control over the name, use braces, e.g., `${1}a`. |
425 | | /// |
426 | | /// To write a literal `$` use `$$`. |
427 | | /// |
428 | | /// # Examples |
429 | | /// |
430 | | /// Note that this function is polymorphic with respect to the replacement. |
431 | | /// In typical usage, this can just be a normal string: |
432 | | /// |
433 | | /// ```rust |
434 | | /// # use regex::Regex; |
435 | | /// # fn main() { |
436 | | /// let re = Regex::new("[^01]+").unwrap(); |
437 | | /// assert_eq!(re.replace("1078910", ""), "1010"); |
438 | | /// # } |
439 | | /// ``` |
440 | | /// |
441 | | /// But anything satisfying the `Replacer` trait will work. For example, |
442 | | /// a closure of type `|&Captures| -> String` provides direct access to the |
443 | | /// captures corresponding to a match. This allows one to access |
444 | | /// capturing group matches easily: |
445 | | /// |
446 | | /// ```rust |
447 | | /// # use regex::Regex; |
448 | | /// # use regex::Captures; fn main() { |
449 | | /// let re = Regex::new(r"([^,\s]+),\s+(\S+)").unwrap(); |
450 | | /// let result = re.replace("Springsteen, Bruce", |caps: &Captures| { |
451 | | /// format!("{} {}", &caps[2], &caps[1]) |
452 | | /// }); |
453 | | /// assert_eq!(result, "Bruce Springsteen"); |
454 | | /// # } |
455 | | /// ``` |
456 | | /// |
457 | | /// But this is a bit cumbersome to use all the time. Instead, a simple |
458 | | /// syntax is supported that expands `$name` into the corresponding capture |
459 | | /// group. Here's the last example, but using this expansion technique |
460 | | /// with named capture groups: |
461 | | /// |
462 | | /// ```rust |
463 | | /// # use regex::Regex; |
464 | | /// # fn main() { |
465 | | /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)").unwrap(); |
466 | | /// let result = re.replace("Springsteen, Bruce", "$first $last"); |
467 | | /// assert_eq!(result, "Bruce Springsteen"); |
468 | | /// # } |
469 | | /// ``` |
470 | | /// |
471 | | /// Note that using `$2` instead of `$first` or `$1` instead of `$last` |
472 | | /// would produce the same result. To write a literal `$` use `$$`. |
473 | | /// |
474 | | /// Sometimes the replacement string requires use of curly braces to |
475 | | /// delineate a capture group replacement and surrounding literal text. |
476 | | /// For example, if we wanted to join two words together with an |
477 | | /// underscore: |
478 | | /// |
479 | | /// ```rust |
480 | | /// # use regex::Regex; |
481 | | /// # fn main() { |
482 | | /// let re = Regex::new(r"(?P<first>\w+)\s+(?P<second>\w+)").unwrap(); |
483 | | /// let result = re.replace("deep fried", "${first}_$second"); |
484 | | /// assert_eq!(result, "deep_fried"); |
485 | | /// # } |
486 | | /// ``` |
487 | | /// |
488 | | /// Without the curly braces, the capture group name `first_` would be |
489 | | /// used, and since it doesn't exist, it would be replaced with the empty |
490 | | /// string. |
491 | | /// |
492 | | /// Finally, sometimes you just want to replace a literal string with no |
493 | | /// regard for capturing group expansion. This can be done by wrapping a |
494 | | /// byte string with `NoExpand`: |
495 | | /// |
496 | | /// ```rust |
497 | | /// # use regex::Regex; |
498 | | /// # fn main() { |
499 | | /// use regex::NoExpand; |
500 | | /// |
501 | | /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(\S+)").unwrap(); |
502 | | /// let result = re.replace("Springsteen, Bruce", NoExpand("$2 $last")); |
503 | | /// assert_eq!(result, "$2 $last"); |
504 | | /// # } |
505 | | /// ``` |
506 | 0 | pub fn replace<'t, R: Replacer>( |
507 | 0 | &self, |
508 | 0 | text: &'t str, |
509 | 0 | rep: R, |
510 | 0 | ) -> Cow<'t, str> { |
511 | 0 | self.replacen(text, 1, rep) |
512 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::replace::<_> Unexecuted instantiation: <regex::re_unicode::Regex>::replace::<_> |
513 | | |
514 | | /// Replaces all non-overlapping matches in `text` with the replacement |
515 | | /// provided. This is the same as calling `replacen` with `limit` set to |
516 | | /// `0`. |
517 | | /// |
518 | | /// See the documentation for `replace` for details on how to access |
519 | | /// capturing group matches in the replacement string. |
520 | 0 | pub fn replace_all<'t, R: Replacer>( |
521 | 0 | &self, |
522 | 0 | text: &'t str, |
523 | 0 | rep: R, |
524 | 0 | ) -> Cow<'t, str> { |
525 | 0 | self.replacen(text, 0, rep) |
526 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::replace_all::<_> Unexecuted instantiation: <regex::re_unicode::Regex>::replace_all::<_> |
527 | | |
528 | | /// Replaces at most `limit` non-overlapping matches in `text` with the |
529 | | /// replacement provided. If `limit` is 0, then all non-overlapping matches |
530 | | /// are replaced. |
531 | | /// |
532 | | /// See the documentation for `replace` for details on how to access |
533 | | /// capturing group matches in the replacement string. |
534 | 0 | pub fn replacen<'t, R: Replacer>( |
535 | 0 | &self, |
536 | 0 | text: &'t str, |
537 | 0 | limit: usize, |
538 | 0 | mut rep: R, |
539 | 0 | ) -> Cow<'t, str> { |
540 | | // If we know that the replacement doesn't have any capture expansions, |
541 | | // then we can use the fast path. The fast path can make a tremendous |
542 | | // difference: |
543 | | // |
544 | | // 1) We use `find_iter` instead of `captures_iter`. Not asking for |
545 | | // captures generally makes the regex engines faster. |
546 | | // 2) We don't need to look up all of the capture groups and do |
547 | | // replacements inside the replacement string. We just push it |
548 | | // at each match and be done with it. |
549 | 0 | if let Some(rep) = rep.no_expansion() { |
550 | 0 | let mut it = self.find_iter(text).enumerate().peekable(); |
551 | 0 | if it.peek().is_none() { |
552 | 0 | return Cow::Borrowed(text); |
553 | 0 | } |
554 | 0 | let mut new = String::with_capacity(text.len()); |
555 | 0 | let mut last_match = 0; |
556 | 0 | for (i, m) in it { |
557 | 0 | if limit > 0 && i >= limit { |
558 | 0 | break; |
559 | 0 | } |
560 | 0 | new.push_str(&text[last_match..m.start()]); |
561 | 0 | new.push_str(&rep); |
562 | 0 | last_match = m.end(); |
563 | | } |
564 | 0 | new.push_str(&text[last_match..]); |
565 | 0 | return Cow::Owned(new); |
566 | 0 | } |
567 | 0 |
|
568 | 0 | // The slower path, which we use if the replacement needs access to |
569 | 0 | // capture groups. |
570 | 0 | let mut it = self.captures_iter(text).enumerate().peekable(); |
571 | 0 | if it.peek().is_none() { |
572 | 0 | return Cow::Borrowed(text); |
573 | 0 | } |
574 | 0 | let mut new = String::with_capacity(text.len()); |
575 | 0 | let mut last_match = 0; |
576 | 0 | for (i, cap) in it { |
577 | 0 | if limit > 0 && i >= limit { |
578 | 0 | break; |
579 | 0 | } |
580 | 0 | // unwrap on 0 is OK because captures only reports matches |
581 | 0 | let m = cap.get(0).unwrap(); |
582 | 0 | new.push_str(&text[last_match..m.start()]); |
583 | 0 | rep.replace_append(&cap, &mut new); |
584 | 0 | last_match = m.end(); |
585 | | } |
586 | 0 | new.push_str(&text[last_match..]); |
587 | 0 | Cow::Owned(new) |
588 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::replacen::<_> Unexecuted instantiation: <regex::re_unicode::Regex>::replacen::<_> |
589 | | } |
590 | | |
591 | | /// Advanced or "lower level" search methods. |
592 | | impl Regex { |
593 | | /// Returns the end location of a match in the text given. |
594 | | /// |
595 | | /// This method may have the same performance characteristics as |
596 | | /// `is_match`, except it provides an end location for a match. In |
597 | | /// particular, the location returned *may be shorter* than the proper end |
598 | | /// of the leftmost-first match. |
599 | | /// |
600 | | /// # Example |
601 | | /// |
602 | | /// Typically, `a+` would match the entire first sequence of `a` in some |
603 | | /// text, but `shortest_match` can give up as soon as it sees the first |
604 | | /// `a`. |
605 | | /// |
606 | | /// ```rust |
607 | | /// # use regex::Regex; |
608 | | /// # fn main() { |
609 | | /// let text = "aaaaa"; |
610 | | /// let pos = Regex::new(r"a+").unwrap().shortest_match(text); |
611 | | /// assert_eq!(pos, Some(1)); |
612 | | /// # } |
613 | | /// ``` |
614 | 0 | pub fn shortest_match(&self, text: &str) -> Option<usize> { |
615 | 0 | self.shortest_match_at(text, 0) |
616 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::shortest_match Unexecuted instantiation: <regex::re_unicode::Regex>::shortest_match |
617 | | |
618 | | /// Returns the same as shortest_match, but starts the search at the given |
619 | | /// offset. |
620 | | /// |
621 | | /// The significance of the starting point is that it takes the surrounding |
622 | | /// context into consideration. For example, the `\A` anchor can only |
623 | | /// match when `start == 0`. |
624 | 0 | pub fn shortest_match_at( |
625 | 0 | &self, |
626 | 0 | text: &str, |
627 | 0 | start: usize, |
628 | 0 | ) -> Option<usize> { |
629 | 0 | self.0.searcher_str().shortest_match_at(text, start) |
630 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::shortest_match_at Unexecuted instantiation: <regex::re_unicode::Regex>::shortest_match_at |
631 | | |
632 | | /// Returns the same as is_match, but starts the search at the given |
633 | | /// offset. |
634 | | /// |
635 | | /// The significance of the starting point is that it takes the surrounding |
636 | | /// context into consideration. For example, the `\A` anchor can only |
637 | | /// match when `start == 0`. |
638 | 0 | pub fn is_match_at(&self, text: &str, start: usize) -> bool { |
639 | 0 | self.shortest_match_at(text, start).is_some() |
640 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::is_match_at Unexecuted instantiation: <regex::re_unicode::Regex>::is_match_at |
641 | | |
642 | | /// Returns the same as find, but starts the search at the given |
643 | | /// offset. |
644 | | /// |
645 | | /// The significance of the starting point is that it takes the surrounding |
646 | | /// context into consideration. For example, the `\A` anchor can only |
647 | | /// match when `start == 0`. |
648 | 0 | pub fn find_at<'t>( |
649 | 0 | &self, |
650 | 0 | text: &'t str, |
651 | 0 | start: usize, |
652 | 0 | ) -> Option<Match<'t>> { |
653 | 0 | self.0 |
654 | 0 | .searcher_str() |
655 | 0 | .find_at(text, start) |
656 | 0 | .map(|(s, e)| Match::new(text, s, e)) Unexecuted instantiation: <regex::re_unicode::Regex>::find_at::{closure#0} Unexecuted instantiation: <regex::re_unicode::Regex>::find_at::{closure#0} |
657 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::find_at Unexecuted instantiation: <regex::re_unicode::Regex>::find_at |
658 | | |
659 | | /// This is like `captures`, but uses |
660 | | /// [`CaptureLocations`](struct.CaptureLocations.html) |
661 | | /// instead of |
662 | | /// [`Captures`](struct.Captures.html) in order to amortize allocations. |
663 | | /// |
664 | | /// To create a `CaptureLocations` value, use the |
665 | | /// `Regex::capture_locations` method. |
666 | | /// |
667 | | /// This returns the overall match if this was successful, which is always |
668 | | /// equivalence to the `0`th capture group. |
669 | 0 | pub fn captures_read<'t>( |
670 | 0 | &self, |
671 | 0 | locs: &mut CaptureLocations, |
672 | 0 | text: &'t str, |
673 | 0 | ) -> Option<Match<'t>> { |
674 | 0 | self.captures_read_at(locs, text, 0) |
675 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::captures_read Unexecuted instantiation: <regex::re_unicode::Regex>::captures_read |
676 | | |
677 | | /// Returns the same as captures, but starts the search at the given |
678 | | /// offset and populates the capture locations given. |
679 | | /// |
680 | | /// The significance of the starting point is that it takes the surrounding |
681 | | /// context into consideration. For example, the `\A` anchor can only |
682 | | /// match when `start == 0`. |
683 | 78.7k | pub fn captures_read_at<'t>( |
684 | 78.7k | &self, |
685 | 78.7k | locs: &mut CaptureLocations, |
686 | 78.7k | text: &'t str, |
687 | 78.7k | start: usize, |
688 | 78.7k | ) -> Option<Match<'t>> { |
689 | 78.7k | self.0 |
690 | 78.7k | .searcher_str() |
691 | 78.7k | .captures_read_at(&mut locs.0, text, start) |
692 | 78.7k | .map(|(s, e)| Match::new(text, s, e)) <regex::re_unicode::Regex>::captures_read_at::{closure#0} Line | Count | Source | 692 | 28.9k | .map(|(s, e)| Match::new(text, s, e)) |
<regex::re_unicode::Regex>::captures_read_at::{closure#0} Line | Count | Source | 692 | 1.50k | .map(|(s, e)| Match::new(text, s, e)) |
|
693 | 78.7k | } <regex::re_unicode::Regex>::captures_read_at Line | Count | Source | 683 | 75.5k | pub fn captures_read_at<'t>( | 684 | 75.5k | &self, | 685 | 75.5k | locs: &mut CaptureLocations, | 686 | 75.5k | text: &'t str, | 687 | 75.5k | start: usize, | 688 | 75.5k | ) -> Option<Match<'t>> { | 689 | 75.5k | self.0 | 690 | 75.5k | .searcher_str() | 691 | 75.5k | .captures_read_at(&mut locs.0, text, start) | 692 | 75.5k | .map(|(s, e)| Match::new(text, s, e)) | 693 | 75.5k | } |
<regex::re_unicode::Regex>::captures_read_at Line | Count | Source | 683 | 3.15k | pub fn captures_read_at<'t>( | 684 | 3.15k | &self, | 685 | 3.15k | locs: &mut CaptureLocations, | 686 | 3.15k | text: &'t str, | 687 | 3.15k | start: usize, | 688 | 3.15k | ) -> Option<Match<'t>> { | 689 | 3.15k | self.0 | 690 | 3.15k | .searcher_str() | 691 | 3.15k | .captures_read_at(&mut locs.0, text, start) | 692 | 3.15k | .map(|(s, e)| Match::new(text, s, e)) | 693 | 3.15k | } |
|
694 | | |
695 | | /// An undocumented alias for `captures_read_at`. |
696 | | /// |
697 | | /// The `regex-capi` crate previously used this routine, so to avoid |
698 | | /// breaking that crate, we continue to provide the name as an undocumented |
699 | | /// alias. |
700 | | #[doc(hidden)] |
701 | 0 | pub fn read_captures_at<'t>( |
702 | 0 | &self, |
703 | 0 | locs: &mut CaptureLocations, |
704 | 0 | text: &'t str, |
705 | 0 | start: usize, |
706 | 0 | ) -> Option<Match<'t>> { |
707 | 0 | self.captures_read_at(locs, text, start) |
708 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::read_captures_at Unexecuted instantiation: <regex::re_unicode::Regex>::read_captures_at |
709 | | } |
710 | | |
711 | | /// Auxiliary methods. |
712 | | impl Regex { |
713 | | /// Returns the original string of this regex. |
714 | 0 | pub fn as_str(&self) -> &str { |
715 | 0 | &self.0.regex_strings()[0] |
716 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::as_str Unexecuted instantiation: <regex::re_unicode::Regex>::as_str |
717 | | |
718 | | /// Returns an iterator over the capture names. |
719 | 0 | pub fn capture_names(&self) -> CaptureNames<'_> { |
720 | 0 | CaptureNames(self.0.capture_names().iter()) |
721 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::capture_names Unexecuted instantiation: <regex::re_unicode::Regex>::capture_names |
722 | | |
723 | | /// Returns the number of captures. |
724 | 0 | pub fn captures_len(&self) -> usize { |
725 | 0 | self.0.capture_names().len() |
726 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::captures_len Unexecuted instantiation: <regex::re_unicode::Regex>::captures_len |
727 | | |
728 | | /// Returns an empty set of capture locations that can be reused in |
729 | | /// multiple calls to `captures_read` or `captures_read_at`. |
730 | 78.7k | pub fn capture_locations(&self) -> CaptureLocations { |
731 | 78.7k | CaptureLocations(self.0.searcher_str().locations()) |
732 | 78.7k | } <regex::re_unicode::Regex>::capture_locations Line | Count | Source | 730 | 75.5k | pub fn capture_locations(&self) -> CaptureLocations { | 731 | 75.5k | CaptureLocations(self.0.searcher_str().locations()) | 732 | 75.5k | } |
<regex::re_unicode::Regex>::capture_locations Line | Count | Source | 730 | 3.15k | pub fn capture_locations(&self) -> CaptureLocations { | 731 | 3.15k | CaptureLocations(self.0.searcher_str().locations()) | 732 | 3.15k | } |
|
733 | | |
734 | | /// An alias for `capture_locations` to preserve backward compatibility. |
735 | | /// |
736 | | /// The `regex-capi` crate uses this method, so to avoid breaking that |
737 | | /// crate, we continue to export it as an undocumented API. |
738 | | #[doc(hidden)] |
739 | 0 | pub fn locations(&self) -> CaptureLocations { |
740 | 0 | CaptureLocations(self.0.searcher_str().locations()) |
741 | 0 | } Unexecuted instantiation: <regex::re_unicode::Regex>::locations Unexecuted instantiation: <regex::re_unicode::Regex>::locations |
742 | | } |
743 | | |
744 | | /// An iterator over the names of all possible captures. |
745 | | /// |
746 | | /// `None` indicates an unnamed capture; the first element (capture 0, the |
747 | | /// whole matched region) is always unnamed. |
748 | | /// |
749 | | /// `'r` is the lifetime of the compiled regular expression. |
750 | | #[derive(Clone, Debug)] |
751 | | pub struct CaptureNames<'r>(::std::slice::Iter<'r, Option<String>>); |
752 | | |
753 | | impl<'r> Iterator for CaptureNames<'r> { |
754 | | type Item = Option<&'r str>; |
755 | | |
756 | 0 | fn next(&mut self) -> Option<Option<&'r str>> { |
757 | 0 | self.0 |
758 | 0 | .next() |
759 | 0 | .as_ref() |
760 | 0 | .map(|slot| slot.as_ref().map(|name| name.as_ref())) Unexecuted instantiation: <regex::re_unicode::CaptureNames as core::iter::traits::iterator::Iterator>::next::{closure#0} Unexecuted instantiation: <regex::re_unicode::CaptureNames as core::iter::traits::iterator::Iterator>::next::{closure#0} Unexecuted instantiation: <regex::re_unicode::CaptureNames as core::iter::traits::iterator::Iterator>::next::{closure#0}::{closure#0} Unexecuted instantiation: <regex::re_unicode::CaptureNames as core::iter::traits::iterator::Iterator>::next::{closure#0}::{closure#0} |
761 | 0 | } Unexecuted instantiation: <regex::re_unicode::CaptureNames as core::iter::traits::iterator::Iterator>::next Unexecuted instantiation: <regex::re_unicode::CaptureNames as core::iter::traits::iterator::Iterator>::next |
762 | | |
763 | 0 | fn size_hint(&self) -> (usize, Option<usize>) { |
764 | 0 | self.0.size_hint() |
765 | 0 | } Unexecuted instantiation: <regex::re_unicode::CaptureNames as core::iter::traits::iterator::Iterator>::size_hint Unexecuted instantiation: <regex::re_unicode::CaptureNames as core::iter::traits::iterator::Iterator>::size_hint |
766 | | |
767 | 0 | fn count(self) -> usize { |
768 | 0 | self.0.count() |
769 | 0 | } Unexecuted instantiation: <regex::re_unicode::CaptureNames as core::iter::traits::iterator::Iterator>::count Unexecuted instantiation: <regex::re_unicode::CaptureNames as core::iter::traits::iterator::Iterator>::count |
770 | | } |
771 | | |
772 | | impl<'r> ExactSizeIterator for CaptureNames<'r> {} |
773 | | |
774 | | impl<'r> FusedIterator for CaptureNames<'r> {} |
775 | | |
776 | | /// Yields all substrings delimited by a regular expression match. |
777 | | /// |
778 | | /// `'r` is the lifetime of the compiled regular expression and `'t` is the |
779 | | /// lifetime of the string being split. |
780 | | #[derive(Debug)] |
781 | | pub struct Split<'r, 't> { |
782 | | finder: Matches<'r, 't>, |
783 | | last: usize, |
784 | | } |
785 | | |
786 | | impl<'r, 't> Iterator for Split<'r, 't> { |
787 | | type Item = &'t str; |
788 | | |
789 | 0 | fn next(&mut self) -> Option<&'t str> { |
790 | 0 | let text = self.finder.0.text(); |
791 | 0 | match self.finder.next() { |
792 | | None => { |
793 | 0 | if self.last > text.len() { |
794 | 0 | None |
795 | | } else { |
796 | 0 | let s = &text[self.last..]; |
797 | 0 | self.last = text.len() + 1; // Next call will return None |
798 | 0 | Some(s) |
799 | | } |
800 | | } |
801 | 0 | Some(m) => { |
802 | 0 | let matched = &text[self.last..m.start()]; |
803 | 0 | self.last = m.end(); |
804 | 0 | Some(matched) |
805 | | } |
806 | | } |
807 | 0 | } Unexecuted instantiation: <regex::re_unicode::Split as core::iter::traits::iterator::Iterator>::next Unexecuted instantiation: <regex::re_unicode::Split as core::iter::traits::iterator::Iterator>::next |
808 | | } |
809 | | |
810 | | impl<'r, 't> FusedIterator for Split<'r, 't> {} |
811 | | |
812 | | /// Yields at most `N` substrings delimited by a regular expression match. |
813 | | /// |
814 | | /// The last substring will be whatever remains after splitting. |
815 | | /// |
816 | | /// `'r` is the lifetime of the compiled regular expression and `'t` is the |
817 | | /// lifetime of the string being split. |
818 | | #[derive(Debug)] |
819 | | pub struct SplitN<'r, 't> { |
820 | | splits: Split<'r, 't>, |
821 | | n: usize, |
822 | | } |
823 | | |
824 | | impl<'r, 't> Iterator for SplitN<'r, 't> { |
825 | | type Item = &'t str; |
826 | | |
827 | 0 | fn next(&mut self) -> Option<&'t str> { |
828 | 0 | if self.n == 0 { |
829 | 0 | return None; |
830 | 0 | } |
831 | 0 |
|
832 | 0 | self.n -= 1; |
833 | 0 | if self.n > 0 { |
834 | 0 | return self.splits.next(); |
835 | 0 | } |
836 | 0 |
|
837 | 0 | let text = self.splits.finder.0.text(); |
838 | 0 | if self.splits.last > text.len() { |
839 | | // We've already returned all substrings. |
840 | 0 | None |
841 | | } else { |
842 | | // self.n == 0, so future calls will return None immediately |
843 | 0 | Some(&text[self.splits.last..]) |
844 | | } |
845 | 0 | } Unexecuted instantiation: <regex::re_unicode::SplitN as core::iter::traits::iterator::Iterator>::next Unexecuted instantiation: <regex::re_unicode::SplitN as core::iter::traits::iterator::Iterator>::next |
846 | | |
847 | 0 | fn size_hint(&self) -> (usize, Option<usize>) { |
848 | 0 | (0, Some(self.n)) |
849 | 0 | } Unexecuted instantiation: <regex::re_unicode::SplitN as core::iter::traits::iterator::Iterator>::size_hint Unexecuted instantiation: <regex::re_unicode::SplitN as core::iter::traits::iterator::Iterator>::size_hint |
850 | | } |
851 | | |
852 | | impl<'r, 't> FusedIterator for SplitN<'r, 't> {} |
853 | | |
854 | | /// CaptureLocations is a low level representation of the raw offsets of each |
855 | | /// submatch. |
856 | | /// |
857 | | /// You can think of this as a lower level |
858 | | /// [`Captures`](struct.Captures.html), where this type does not support |
859 | | /// named capturing groups directly and it does not borrow the text that these |
860 | | /// offsets were matched on. |
861 | | /// |
862 | | /// Primarily, this type is useful when using the lower level `Regex` APIs |
863 | | /// such as `read_captures`, which permits amortizing the allocation in which |
864 | | /// capture match locations are stored. |
865 | | /// |
866 | | /// In order to build a value of this type, you'll need to call the |
867 | | /// `capture_locations` method on the `Regex` being used to execute the search. |
868 | | /// The value returned can then be reused in subsequent searches. |
869 | | #[derive(Clone, Debug)] |
870 | | pub struct CaptureLocations(re_trait::Locations); |
871 | | |
872 | | /// A type alias for `CaptureLocations` for backwards compatibility. |
873 | | /// |
874 | | /// Previously, we exported `CaptureLocations` as `Locations` in an |
875 | | /// undocumented API. To prevent breaking that code (e.g., in `regex-capi`), |
876 | | /// we continue re-exporting the same undocumented API. |
877 | | #[doc(hidden)] |
878 | | pub type Locations = CaptureLocations; |
879 | | |
880 | | impl CaptureLocations { |
881 | | /// Returns the start and end positions of the Nth capture group. Returns |
882 | | /// `None` if `i` is not a valid capture group or if the capture group did |
883 | | /// not match anything. The positions returned are *always* byte indices |
884 | | /// with respect to the original string matched. |
885 | | #[inline] |
886 | 0 | pub fn get(&self, i: usize) -> Option<(usize, usize)> { |
887 | 0 | self.0.pos(i) |
888 | 0 | } Unexecuted instantiation: <regex::re_unicode::CaptureLocations>::get Unexecuted instantiation: <regex::re_unicode::CaptureLocations>::get |
889 | | |
890 | | /// Returns the total number of capturing groups. |
891 | | /// |
892 | | /// This is always at least `1` since every regex has at least `1` |
893 | | /// capturing group that corresponds to the entire match. |
894 | | #[inline] |
895 | 0 | pub fn len(&self) -> usize { |
896 | 0 | self.0.len() |
897 | 0 | } Unexecuted instantiation: <regex::re_unicode::CaptureLocations>::len Unexecuted instantiation: <regex::re_unicode::CaptureLocations>::len |
898 | | |
899 | | /// An alias for the `get` method for backwards compatibility. |
900 | | /// |
901 | | /// Previously, we exported `get` as `pos` in an undocumented API. To |
902 | | /// prevent breaking that code (e.g., in `regex-capi`), we continue |
903 | | /// re-exporting the same undocumented API. |
904 | | #[doc(hidden)] |
905 | | #[inline] |
906 | 0 | pub fn pos(&self, i: usize) -> Option<(usize, usize)> { |
907 | 0 | self.get(i) |
908 | 0 | } Unexecuted instantiation: <regex::re_unicode::CaptureLocations>::pos Unexecuted instantiation: <regex::re_unicode::CaptureLocations>::pos |
909 | | } |
910 | | |
911 | | /// Captures represents a group of captured strings for a single match. |
912 | | /// |
913 | | /// The 0th capture always corresponds to the entire match. Each subsequent |
914 | | /// index corresponds to the next capture group in the regex. If a capture |
915 | | /// group is named, then the matched string is *also* available via the `name` |
916 | | /// method. (Note that the 0th capture is always unnamed and so must be |
917 | | /// accessed with the `get` method.) |
918 | | /// |
919 | | /// Positions returned from a capture group are always byte indices. |
920 | | /// |
921 | | /// `'t` is the lifetime of the matched text. |
922 | | pub struct Captures<'t> { |
923 | | text: &'t str, |
924 | | locs: re_trait::Locations, |
925 | | named_groups: Arc<HashMap<String, usize>>, |
926 | | } |
927 | | |
928 | | impl<'t> Captures<'t> { |
929 | | /// Returns the match associated with the capture group at index `i`. If |
930 | | /// `i` does not correspond to a capture group, or if the capture group |
931 | | /// did not participate in the match, then `None` is returned. |
932 | | /// |
933 | | /// # Examples |
934 | | /// |
935 | | /// Get the text of the match with a default of an empty string if this |
936 | | /// group didn't participate in the match: |
937 | | /// |
938 | | /// ```rust |
939 | | /// # use regex::Regex; |
940 | | /// let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap(); |
941 | | /// let caps = re.captures("abc123").unwrap(); |
942 | | /// |
943 | | /// let text1 = caps.get(1).map_or("", |m| m.as_str()); |
944 | | /// let text2 = caps.get(2).map_or("", |m| m.as_str()); |
945 | | /// assert_eq!(text1, "123"); |
946 | | /// assert_eq!(text2, ""); |
947 | | /// ``` |
948 | 82.2k | pub fn get(&self, i: usize) -> Option<Match<'t>> { |
949 | 82.2k | self.locs.pos(i).map(|(s, e)| Match::new(self.text, s, e)) <regex::re_unicode::Captures>::get::{closure#0} Line | Count | Source | 949 | 48.4k | self.locs.pos(i).map(|(s, e)| Match::new(self.text, s, e)) |
<regex::re_unicode::Captures>::get::{closure#0} Line | Count | Source | 949 | 3.12k | self.locs.pos(i).map(|(s, e)| Match::new(self.text, s, e)) |
|
950 | 82.2k | } <regex::re_unicode::Captures>::get Line | Count | Source | 948 | 77.5k | pub fn get(&self, i: usize) -> Option<Match<'t>> { | 949 | 77.5k | self.locs.pos(i).map(|(s, e)| Match::new(self.text, s, e)) | 950 | 77.5k | } |
<regex::re_unicode::Captures>::get Line | Count | Source | 948 | 4.71k | pub fn get(&self, i: usize) -> Option<Match<'t>> { | 949 | 4.71k | self.locs.pos(i).map(|(s, e)| Match::new(self.text, s, e)) | 950 | 4.71k | } |
|
951 | | |
952 | | /// Returns the match for the capture group named `name`. If `name` isn't a |
953 | | /// valid capture group or didn't match anything, then `None` is returned. |
954 | 0 | pub fn name(&self, name: &str) -> Option<Match<'t>> { |
955 | 0 | self.named_groups.get(name).and_then(|&i| self.get(i)) Unexecuted instantiation: <regex::re_unicode::Captures>::name::{closure#0} Unexecuted instantiation: <regex::re_unicode::Captures>::name::{closure#0} |
956 | 0 | } Unexecuted instantiation: <regex::re_unicode::Captures>::name Unexecuted instantiation: <regex::re_unicode::Captures>::name |
957 | | |
958 | | /// An iterator that yields all capturing matches in the order in which |
959 | | /// they appear in the regex. If a particular capture group didn't |
960 | | /// participate in the match, then `None` is yielded for that capture. |
961 | | /// |
962 | | /// The first match always corresponds to the overall match of the regex. |
963 | 0 | pub fn iter<'c>(&'c self) -> SubCaptureMatches<'c, 't> { |
964 | 0 | SubCaptureMatches { caps: self, it: self.locs.iter() } |
965 | 0 | } Unexecuted instantiation: <regex::re_unicode::Captures>::iter Unexecuted instantiation: <regex::re_unicode::Captures>::iter |
966 | | |
967 | | /// Expands all instances of `$name` in `replacement` to the corresponding |
968 | | /// capture group `name`, and writes them to the `dst` buffer given. |
969 | | /// |
970 | | /// `name` may be an integer corresponding to the index of the capture |
971 | | /// group (counted by order of opening parenthesis where `0` is the |
972 | | /// entire match) or it can be a name (consisting of letters, digits or |
973 | | /// underscores) corresponding to a named capture group. |
974 | | /// |
975 | | /// If `name` isn't a valid capture group (whether the name doesn't exist |
976 | | /// or isn't a valid index), then it is replaced with the empty string. |
977 | | /// |
978 | | /// The longest possible name consisting of the characters `[_0-9A-Za-z]` |
979 | | /// is used. e.g., `$1a` looks up the capture group named `1a` and not the |
980 | | /// capture group at index `1`. To exert more precise control over the |
981 | | /// name, or to refer to a capture group name that uses characters outside |
982 | | /// of `[_0-9A-Za-z]`, use braces, e.g., `${1}a` or `${foo[bar].baz}`. When |
983 | | /// using braces, any sequence of characters is permitted. If the sequence |
984 | | /// does not refer to a capture group name in the corresponding regex, then |
985 | | /// it is replaced with an empty string. |
986 | | /// |
987 | | /// To write a literal `$` use `$$`. |
988 | 0 | pub fn expand(&self, replacement: &str, dst: &mut String) { |
989 | 0 | expand_str(self, replacement, dst) |
990 | 0 | } Unexecuted instantiation: <regex::re_unicode::Captures>::expand Unexecuted instantiation: <regex::re_unicode::Captures>::expand |
991 | | |
992 | | /// Returns the number of captured groups. |
993 | | /// |
994 | | /// This is always at least `1`, since every regex has at least one capture |
995 | | /// group that corresponds to the full match. |
996 | | #[inline] |
997 | 0 | pub fn len(&self) -> usize { |
998 | 0 | self.locs.len() |
999 | 0 | } Unexecuted instantiation: <regex::re_unicode::Captures>::len Unexecuted instantiation: <regex::re_unicode::Captures>::len |
1000 | | } |
1001 | | |
1002 | | impl<'t> fmt::Debug for Captures<'t> { |
1003 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
1004 | 0 | f.debug_tuple("Captures").field(&CapturesDebug(self)).finish() |
1005 | 0 | } Unexecuted instantiation: <regex::re_unicode::Captures as core::fmt::Debug>::fmt Unexecuted instantiation: <regex::re_unicode::Captures as core::fmt::Debug>::fmt |
1006 | | } |
1007 | | |
1008 | | struct CapturesDebug<'c, 't>(&'c Captures<'t>); |
1009 | | |
1010 | | impl<'c, 't> fmt::Debug for CapturesDebug<'c, 't> { |
1011 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
1012 | 0 | // We'd like to show something nice here, even if it means an |
1013 | 0 | // allocation to build a reverse index. |
1014 | 0 | let slot_to_name: HashMap<&usize, &String> = |
1015 | 0 | self.0.named_groups.iter().map(|(a, b)| (b, a)).collect(); Unexecuted instantiation: <regex::re_unicode::CapturesDebug as core::fmt::Debug>::fmt::{closure#0} Unexecuted instantiation: <regex::re_unicode::CapturesDebug as core::fmt::Debug>::fmt::{closure#0} |
1016 | 0 | let mut map = f.debug_map(); |
1017 | 0 | for (slot, m) in self.0.locs.iter().enumerate() { |
1018 | 0 | let m = m.map(|(s, e)| &self.0.text[s..e]); Unexecuted instantiation: <regex::re_unicode::CapturesDebug as core::fmt::Debug>::fmt::{closure#1} Unexecuted instantiation: <regex::re_unicode::CapturesDebug as core::fmt::Debug>::fmt::{closure#1} |
1019 | 0 | if let Some(name) = slot_to_name.get(&slot) { |
1020 | 0 | map.entry(&name, &m); |
1021 | 0 | } else { |
1022 | 0 | map.entry(&slot, &m); |
1023 | 0 | } |
1024 | | } |
1025 | 0 | map.finish() |
1026 | 0 | } Unexecuted instantiation: <regex::re_unicode::CapturesDebug as core::fmt::Debug>::fmt Unexecuted instantiation: <regex::re_unicode::CapturesDebug as core::fmt::Debug>::fmt |
1027 | | } |
1028 | | |
1029 | | /// Get a group by index. |
1030 | | /// |
1031 | | /// `'t` is the lifetime of the matched text. |
1032 | | /// |
1033 | | /// The text can't outlive the `Captures` object if this method is |
1034 | | /// used, because of how `Index` is defined (normally `a[i]` is part |
1035 | | /// of `a` and can't outlive it); to do that, use `get()` instead. |
1036 | | /// |
1037 | | /// # Panics |
1038 | | /// |
1039 | | /// If there is no group at the given index. |
1040 | | impl<'t> Index<usize> for Captures<'t> { |
1041 | | type Output = str; |
1042 | | |
1043 | 0 | fn index(&self, i: usize) -> &str { |
1044 | 0 | self.get(i) |
1045 | 0 | .map(|m| m.as_str()) Unexecuted instantiation: <regex::re_unicode::Captures as core::ops::index::Index<usize>>::index::{closure#0} Unexecuted instantiation: <regex::re_unicode::Captures as core::ops::index::Index<usize>>::index::{closure#0} |
1046 | 0 | .unwrap_or_else(|| panic!("no group at index '{}'", i)) Unexecuted instantiation: <regex::re_unicode::Captures as core::ops::index::Index<usize>>::index::{closure#1} Unexecuted instantiation: <regex::re_unicode::Captures as core::ops::index::Index<usize>>::index::{closure#1} |
1047 | 0 | } Unexecuted instantiation: <regex::re_unicode::Captures as core::ops::index::Index<usize>>::index Unexecuted instantiation: <regex::re_unicode::Captures as core::ops::index::Index<usize>>::index |
1048 | | } |
1049 | | |
1050 | | /// Get a group by name. |
1051 | | /// |
1052 | | /// `'t` is the lifetime of the matched text and `'i` is the lifetime |
1053 | | /// of the group name (the index). |
1054 | | /// |
1055 | | /// The text can't outlive the `Captures` object if this method is |
1056 | | /// used, because of how `Index` is defined (normally `a[i]` is part |
1057 | | /// of `a` and can't outlive it); to do that, use `name` instead. |
1058 | | /// |
1059 | | /// # Panics |
1060 | | /// |
1061 | | /// If there is no group named by the given value. |
1062 | | impl<'t, 'i> Index<&'i str> for Captures<'t> { |
1063 | | type Output = str; |
1064 | | |
1065 | 0 | fn index<'a>(&'a self, name: &'i str) -> &'a str { |
1066 | 0 | self.name(name) |
1067 | 0 | .map(|m| m.as_str()) Unexecuted instantiation: <regex::re_unicode::Captures as core::ops::index::Index<&str>>::index::{closure#0} Unexecuted instantiation: <regex::re_unicode::Captures as core::ops::index::Index<&str>>::index::{closure#0} |
1068 | 0 | .unwrap_or_else(|| panic!("no group named '{}'", name)) Unexecuted instantiation: <regex::re_unicode::Captures as core::ops::index::Index<&str>>::index::{closure#1} Unexecuted instantiation: <regex::re_unicode::Captures as core::ops::index::Index<&str>>::index::{closure#1} |
1069 | 0 | } Unexecuted instantiation: <regex::re_unicode::Captures as core::ops::index::Index<&str>>::index Unexecuted instantiation: <regex::re_unicode::Captures as core::ops::index::Index<&str>>::index |
1070 | | } |
1071 | | |
1072 | | /// An iterator that yields all capturing matches in the order in which they |
1073 | | /// appear in the regex. |
1074 | | /// |
1075 | | /// If a particular capture group didn't participate in the match, then `None` |
1076 | | /// is yielded for that capture. The first match always corresponds to the |
1077 | | /// overall match of the regex. |
1078 | | /// |
1079 | | /// The lifetime `'c` corresponds to the lifetime of the `Captures` value, and |
1080 | | /// the lifetime `'t` corresponds to the originally matched text. |
1081 | | #[derive(Clone, Debug)] |
1082 | | pub struct SubCaptureMatches<'c, 't> { |
1083 | | caps: &'c Captures<'t>, |
1084 | | it: SubCapturesPosIter<'c>, |
1085 | | } |
1086 | | |
1087 | | impl<'c, 't> Iterator for SubCaptureMatches<'c, 't> { |
1088 | | type Item = Option<Match<'t>>; |
1089 | | |
1090 | 0 | fn next(&mut self) -> Option<Option<Match<'t>>> { |
1091 | 0 | self.it |
1092 | 0 | .next() |
1093 | 0 | .map(|cap| cap.map(|(s, e)| Match::new(self.caps.text, s, e))) Unexecuted instantiation: <regex::re_unicode::SubCaptureMatches as core::iter::traits::iterator::Iterator>::next::{closure#0} Unexecuted instantiation: <regex::re_unicode::SubCaptureMatches as core::iter::traits::iterator::Iterator>::next::{closure#0} Unexecuted instantiation: <regex::re_unicode::SubCaptureMatches as core::iter::traits::iterator::Iterator>::next::{closure#0}::{closure#0} Unexecuted instantiation: <regex::re_unicode::SubCaptureMatches as core::iter::traits::iterator::Iterator>::next::{closure#0}::{closure#0} |
1094 | 0 | } Unexecuted instantiation: <regex::re_unicode::SubCaptureMatches as core::iter::traits::iterator::Iterator>::next Unexecuted instantiation: <regex::re_unicode::SubCaptureMatches as core::iter::traits::iterator::Iterator>::next |
1095 | | } |
1096 | | |
1097 | | impl<'c, 't> FusedIterator for SubCaptureMatches<'c, 't> {} |
1098 | | |
1099 | | /// An iterator that yields all non-overlapping capture groups matching a |
1100 | | /// particular regular expression. |
1101 | | /// |
1102 | | /// The iterator stops when no more matches can be found. |
1103 | | /// |
1104 | | /// `'r` is the lifetime of the compiled regular expression and `'t` is the |
1105 | | /// lifetime of the matched string. |
1106 | | #[derive(Debug)] |
1107 | | pub struct CaptureMatches<'r, 't>( |
1108 | | re_trait::CaptureMatches<'t, ExecNoSyncStr<'r>>, |
1109 | | ); |
1110 | | |
1111 | | impl<'r, 't> Iterator for CaptureMatches<'r, 't> { |
1112 | | type Item = Captures<'t>; |
1113 | | |
1114 | 0 | fn next(&mut self) -> Option<Captures<'t>> { |
1115 | 0 | self.0.next().map(|locs| Captures { |
1116 | 0 | text: self.0.text(), |
1117 | 0 | locs: locs, |
1118 | 0 | named_groups: self.0.regex().capture_name_idx().clone(), |
1119 | 0 | }) Unexecuted instantiation: <regex::re_unicode::CaptureMatches as core::iter::traits::iterator::Iterator>::next::{closure#0} Unexecuted instantiation: <regex::re_unicode::CaptureMatches as core::iter::traits::iterator::Iterator>::next::{closure#0} |
1120 | 0 | } Unexecuted instantiation: <regex::re_unicode::CaptureMatches as core::iter::traits::iterator::Iterator>::next Unexecuted instantiation: <regex::re_unicode::CaptureMatches as core::iter::traits::iterator::Iterator>::next |
1121 | | } |
1122 | | |
1123 | | impl<'r, 't> FusedIterator for CaptureMatches<'r, 't> {} |
1124 | | |
1125 | | /// An iterator over all non-overlapping matches for a particular string. |
1126 | | /// |
1127 | | /// The iterator yields a `Match` value. The iterator stops when no more |
1128 | | /// matches can be found. |
1129 | | /// |
1130 | | /// `'r` is the lifetime of the compiled regular expression and `'t` is the |
1131 | | /// lifetime of the matched string. |
1132 | | #[derive(Debug)] |
1133 | | pub struct Matches<'r, 't>(re_trait::Matches<'t, ExecNoSyncStr<'r>>); |
1134 | | |
1135 | | impl<'r, 't> Iterator for Matches<'r, 't> { |
1136 | | type Item = Match<'t>; |
1137 | | |
1138 | 0 | fn next(&mut self) -> Option<Match<'t>> { |
1139 | 0 | let text = self.0.text(); |
1140 | 0 | self.0.next().map(|(s, e)| Match::new(text, s, e)) Unexecuted instantiation: <regex::re_unicode::Matches as core::iter::traits::iterator::Iterator>::next::{closure#0} Unexecuted instantiation: <regex::re_unicode::Matches as core::iter::traits::iterator::Iterator>::next::{closure#0} |
1141 | 0 | } Unexecuted instantiation: <regex::re_unicode::Matches as core::iter::traits::iterator::Iterator>::next Unexecuted instantiation: <regex::re_unicode::Matches as core::iter::traits::iterator::Iterator>::next |
1142 | | } |
1143 | | |
1144 | | impl<'r, 't> FusedIterator for Matches<'r, 't> {} |
1145 | | |
1146 | | /// Replacer describes types that can be used to replace matches in a string. |
1147 | | /// |
1148 | | /// In general, users of this crate shouldn't need to implement this trait, |
1149 | | /// since implementations are already provided for `&str` along with other |
1150 | | /// variants of string types and `FnMut(&Captures) -> String` (or any |
1151 | | /// `FnMut(&Captures) -> T` where `T: AsRef<str>`), which covers most use cases. |
1152 | | pub trait Replacer { |
1153 | | /// Appends text to `dst` to replace the current match. |
1154 | | /// |
1155 | | /// The current match is represented by `caps`, which is guaranteed to |
1156 | | /// have a match at capture group `0`. |
1157 | | /// |
1158 | | /// For example, a no-op replacement would be |
1159 | | /// `dst.push_str(caps.get(0).unwrap().as_str())`. |
1160 | | fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String); |
1161 | | |
1162 | | /// Return a fixed unchanging replacement string. |
1163 | | /// |
1164 | | /// When doing replacements, if access to `Captures` is not needed (e.g., |
1165 | | /// the replacement byte string does not need `$` expansion), then it can |
1166 | | /// be beneficial to avoid finding sub-captures. |
1167 | | /// |
1168 | | /// In general, this is called once for every call to `replacen`. |
1169 | 0 | fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, str>> { |
1170 | 0 | None |
1171 | 0 | } Unexecuted instantiation: <_ as regex::re_unicode::Replacer>::no_expansion Unexecuted instantiation: <_ as regex::re_unicode::Replacer>::no_expansion |
1172 | | |
1173 | | /// Return a `Replacer` that borrows and wraps this `Replacer`. |
1174 | | /// |
1175 | | /// This is useful when you want to take a generic `Replacer` (which might |
1176 | | /// not be cloneable) and use it without consuming it, so it can be used |
1177 | | /// more than once. |
1178 | | /// |
1179 | | /// # Example |
1180 | | /// |
1181 | | /// ``` |
1182 | | /// use regex::{Regex, Replacer}; |
1183 | | /// |
1184 | | /// fn replace_all_twice<R: Replacer>( |
1185 | | /// re: Regex, |
1186 | | /// src: &str, |
1187 | | /// mut rep: R, |
1188 | | /// ) -> String { |
1189 | | /// let dst = re.replace_all(src, rep.by_ref()); |
1190 | | /// let dst = re.replace_all(&dst, rep.by_ref()); |
1191 | | /// dst.into_owned() |
1192 | | /// } |
1193 | | /// ``` |
1194 | 0 | fn by_ref<'r>(&'r mut self) -> ReplacerRef<'r, Self> { |
1195 | 0 | ReplacerRef(self) |
1196 | 0 | } Unexecuted instantiation: <_ as regex::re_unicode::Replacer>::by_ref Unexecuted instantiation: <_ as regex::re_unicode::Replacer>::by_ref |
1197 | | } |
1198 | | |
1199 | | /// By-reference adaptor for a `Replacer` |
1200 | | /// |
1201 | | /// Returned by [`Replacer::by_ref`](trait.Replacer.html#method.by_ref). |
1202 | | #[derive(Debug)] |
1203 | | pub struct ReplacerRef<'a, R: ?Sized>(&'a mut R); |
1204 | | |
1205 | | impl<'a, R: Replacer + ?Sized + 'a> Replacer for ReplacerRef<'a, R> { |
1206 | 0 | fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String) { |
1207 | 0 | self.0.replace_append(caps, dst) |
1208 | 0 | } Unexecuted instantiation: <regex::re_unicode::ReplacerRef<_> as regex::re_unicode::Replacer>::replace_append Unexecuted instantiation: <regex::re_unicode::ReplacerRef<_> as regex::re_unicode::Replacer>::replace_append |
1209 | 0 | fn no_expansion(&mut self) -> Option<Cow<'_, str>> { |
1210 | 0 | self.0.no_expansion() |
1211 | 0 | } Unexecuted instantiation: <regex::re_unicode::ReplacerRef<_> as regex::re_unicode::Replacer>::no_expansion Unexecuted instantiation: <regex::re_unicode::ReplacerRef<_> as regex::re_unicode::Replacer>::no_expansion |
1212 | | } |
1213 | | |
1214 | | impl<'a> Replacer for &'a str { |
1215 | 0 | fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String) { |
1216 | 0 | caps.expand(*self, dst); |
1217 | 0 | } Unexecuted instantiation: <&str as regex::re_unicode::Replacer>::replace_append Unexecuted instantiation: <&str as regex::re_unicode::Replacer>::replace_append |
1218 | | |
1219 | 0 | fn no_expansion(&mut self) -> Option<Cow<'_, str>> { |
1220 | 0 | no_expansion(self) |
1221 | 0 | } Unexecuted instantiation: <&str as regex::re_unicode::Replacer>::no_expansion Unexecuted instantiation: <&str as regex::re_unicode::Replacer>::no_expansion |
1222 | | } |
1223 | | |
1224 | | impl<'a> Replacer for &'a String { |
1225 | 0 | fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String) { |
1226 | 0 | self.as_str().replace_append(caps, dst) |
1227 | 0 | } Unexecuted instantiation: <&alloc::string::String as regex::re_unicode::Replacer>::replace_append Unexecuted instantiation: <&alloc::string::String as regex::re_unicode::Replacer>::replace_append |
1228 | | |
1229 | 0 | fn no_expansion(&mut self) -> Option<Cow<'_, str>> { |
1230 | 0 | no_expansion(self) |
1231 | 0 | } Unexecuted instantiation: <&alloc::string::String as regex::re_unicode::Replacer>::no_expansion Unexecuted instantiation: <&alloc::string::String as regex::re_unicode::Replacer>::no_expansion |
1232 | | } |
1233 | | |
1234 | | impl Replacer for String { |
1235 | 0 | fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String) { |
1236 | 0 | self.as_str().replace_append(caps, dst) |
1237 | 0 | } Unexecuted instantiation: <alloc::string::String as regex::re_unicode::Replacer>::replace_append Unexecuted instantiation: <alloc::string::String as regex::re_unicode::Replacer>::replace_append |
1238 | | |
1239 | 0 | fn no_expansion(&mut self) -> Option<Cow<'_, str>> { |
1240 | 0 | no_expansion(self) |
1241 | 0 | } Unexecuted instantiation: <alloc::string::String as regex::re_unicode::Replacer>::no_expansion Unexecuted instantiation: <alloc::string::String as regex::re_unicode::Replacer>::no_expansion |
1242 | | } |
1243 | | |
1244 | | impl<'a> Replacer for Cow<'a, str> { |
1245 | 0 | fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String) { |
1246 | 0 | self.as_ref().replace_append(caps, dst) |
1247 | 0 | } Unexecuted instantiation: <alloc::borrow::Cow<str> as regex::re_unicode::Replacer>::replace_append Unexecuted instantiation: <alloc::borrow::Cow<str> as regex::re_unicode::Replacer>::replace_append |
1248 | | |
1249 | 0 | fn no_expansion(&mut self) -> Option<Cow<'_, str>> { |
1250 | 0 | no_expansion(self) |
1251 | 0 | } Unexecuted instantiation: <alloc::borrow::Cow<str> as regex::re_unicode::Replacer>::no_expansion Unexecuted instantiation: <alloc::borrow::Cow<str> as regex::re_unicode::Replacer>::no_expansion |
1252 | | } |
1253 | | |
1254 | | impl<'a> Replacer for &'a Cow<'a, str> { |
1255 | 0 | fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String) { |
1256 | 0 | self.as_ref().replace_append(caps, dst) |
1257 | 0 | } Unexecuted instantiation: <&alloc::borrow::Cow<str> as regex::re_unicode::Replacer>::replace_append Unexecuted instantiation: <&alloc::borrow::Cow<str> as regex::re_unicode::Replacer>::replace_append |
1258 | | |
1259 | 0 | fn no_expansion(&mut self) -> Option<Cow<'_, str>> { |
1260 | 0 | no_expansion(self) |
1261 | 0 | } Unexecuted instantiation: <&alloc::borrow::Cow<str> as regex::re_unicode::Replacer>::no_expansion Unexecuted instantiation: <&alloc::borrow::Cow<str> as regex::re_unicode::Replacer>::no_expansion |
1262 | | } |
1263 | | |
1264 | 0 | fn no_expansion<T: AsRef<str>>(t: &T) -> Option<Cow<'_, str>> { |
1265 | 0 | let s = t.as_ref(); |
1266 | 0 | match find_byte(b'$', s.as_bytes()) { |
1267 | 0 | Some(_) => None, |
1268 | 0 | None => Some(Cow::Borrowed(s)), |
1269 | | } |
1270 | 0 | } Unexecuted instantiation: regex::re_unicode::no_expansion::<alloc::borrow::Cow<str>> Unexecuted instantiation: regex::re_unicode::no_expansion::<alloc::string::String> Unexecuted instantiation: regex::re_unicode::no_expansion::<&alloc::borrow::Cow<str>> Unexecuted instantiation: regex::re_unicode::no_expansion::<&alloc::string::String> Unexecuted instantiation: regex::re_unicode::no_expansion::<&str> Unexecuted instantiation: regex::re_unicode::no_expansion::<alloc::borrow::Cow<str>> Unexecuted instantiation: regex::re_unicode::no_expansion::<alloc::string::String> Unexecuted instantiation: regex::re_unicode::no_expansion::<&alloc::borrow::Cow<str>> Unexecuted instantiation: regex::re_unicode::no_expansion::<&alloc::string::String> Unexecuted instantiation: regex::re_unicode::no_expansion::<&str> |
1271 | | |
1272 | | impl<F, T> Replacer for F |
1273 | | where |
1274 | | F: FnMut(&Captures<'_>) -> T, |
1275 | | T: AsRef<str>, |
1276 | | { |
1277 | 0 | fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String) { |
1278 | 0 | dst.push_str((*self)(caps).as_ref()); |
1279 | 0 | } Unexecuted instantiation: <_ as regex::re_unicode::Replacer>::replace_append Unexecuted instantiation: <_ as regex::re_unicode::Replacer>::replace_append |
1280 | | } |
1281 | | |
1282 | | /// `NoExpand` indicates literal string replacement. |
1283 | | /// |
1284 | | /// It can be used with `replace` and `replace_all` to do a literal string |
1285 | | /// replacement without expanding `$name` to their corresponding capture |
1286 | | /// groups. This can be both convenient (to avoid escaping `$`, for example) |
1287 | | /// and performant (since capture groups don't need to be found). |
1288 | | /// |
1289 | | /// `'t` is the lifetime of the literal text. |
1290 | | #[derive(Clone, Debug)] |
1291 | | pub struct NoExpand<'t>(pub &'t str); |
1292 | | |
1293 | | impl<'t> Replacer for NoExpand<'t> { |
1294 | 0 | fn replace_append(&mut self, _: &Captures<'_>, dst: &mut String) { |
1295 | 0 | dst.push_str(self.0); |
1296 | 0 | } Unexecuted instantiation: <regex::re_unicode::NoExpand as regex::re_unicode::Replacer>::replace_append Unexecuted instantiation: <regex::re_unicode::NoExpand as regex::re_unicode::Replacer>::replace_append |
1297 | | |
1298 | 0 | fn no_expansion(&mut self) -> Option<Cow<'_, str>> { |
1299 | 0 | Some(Cow::Borrowed(self.0)) |
1300 | 0 | } Unexecuted instantiation: <regex::re_unicode::NoExpand as regex::re_unicode::Replacer>::no_expansion Unexecuted instantiation: <regex::re_unicode::NoExpand as regex::re_unicode::Replacer>::no_expansion |
1301 | | } |