1use alloc::{borrow::Cow, string::String, sync::Arc, vec::Vec};
2
3use regex_automata::{meta, util::captures, Input, PatternID};
4
5use crate::{bytes::RegexBuilder, error::Error};
6
7/// A compiled regular expression for searching Unicode haystacks.
8///
9/// A `Regex` can be used to search haystacks, split haystacks into substrings
10/// or replace substrings in a haystack with a different substring. All
11/// searching is done with an implicit `(?s:.)*?` at the beginning and end of
12/// an pattern. To force an expression to match the whole string (or a prefix
13/// or a suffix), you must use an anchor like `^` or `$` (or `\A` and `\z`).
14///
15/// Like the `Regex` type in the parent module, matches with this regex return
16/// byte offsets into the haystack. **Unlike** the parent `Regex` type, these
17/// byte offsets may not correspond to UTF-8 sequence boundaries since the
18/// regexes in this module can match arbitrary bytes.
19///
20/// The only methods that allocate new byte strings are the string replacement
21/// methods. All other methods (searching and splitting) return borrowed
22/// references into the haystack given.
23///
24/// # Example
25///
26/// Find the offsets of a US phone number:
27///
28/// ```
29/// use regex::bytes::Regex;
30///
31/// let re = Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}").unwrap();
32/// let m = re.find(b"phone: 111-222-3333").unwrap();
33/// assert_eq!(7..19, m.range());
34/// ```
35///
36/// # Example: extracting capture groups
37///
38/// A common way to use regexes is with capture groups. That is, instead of
39/// just looking for matches of an entire regex, parentheses are used to create
40/// groups that represent part of the match.
41///
42/// For example, consider a haystack with multiple lines, and each line has
43/// three whitespace delimited fields where the second field is expected to be
44/// a number and the third field a boolean. To make this convenient, we use
45/// the [`Captures::extract`] API to put the strings that match each group
46/// into a fixed size array:
47///
48/// ```
49/// use regex::bytes::Regex;
50///
51/// let hay = b"
52/// rabbit 54 true
53/// groundhog 2 true
54/// does not match
55/// fox 109 false
56/// ";
57/// let re = Regex::new(r"(?m)^\s*(\S+)\s+([0-9]+)\s+(true|false)\s*$").unwrap();
58/// let mut fields: Vec<(&[u8], i64, bool)> = vec![];
59/// for (_, [f1, f2, f3]) in re.captures_iter(hay).map(|caps| caps.extract()) {
60/// // These unwraps are OK because our pattern is written in a way where
61/// // all matches for f2 and f3 will be valid UTF-8.
62/// let f2 = std::str::from_utf8(f2).unwrap();
63/// let f3 = std::str::from_utf8(f3).unwrap();
64/// fields.push((f1, f2.parse()?, f3.parse()?));
65/// }
66/// assert_eq!(fields, vec![
67/// (&b"rabbit"[..], 54, true),
68/// (&b"groundhog"[..], 2, true),
69/// (&b"fox"[..], 109, false),
70/// ]);
71///
72/// # Ok::<(), Box<dyn std::error::Error>>(())
73/// ```
74///
75/// # Example: matching invalid UTF-8
76///
77/// One of the reasons for searching `&[u8]` haystacks is that the `&[u8]`
78/// might not be valid UTF-8. Indeed, with a `bytes::Regex`, patterns that
79/// match invalid UTF-8 are explicitly allowed. Here's one example that looks
80/// for valid UTF-8 fields that might be separated by invalid UTF-8. In this
81/// case, we use `(?s-u:.)`, which matches any byte. Attempting to use it in a
82/// top-level `Regex` will result in the regex failing to compile. Notice also
83/// that we use `.` with Unicode mode enabled, in which case, only valid UTF-8
84/// is matched. In this way, we can build one pattern where some parts only
85/// match valid UTF-8 while other parts are more permissive.
86///
87/// ```
88/// use regex::bytes::Regex;
89///
90/// // F0 9F 92 A9 is the UTF-8 encoding for a Pile of Poo.
91/// let hay = b"\xFF\xFFfoo\xFF\xFF\xFF\xF0\x9F\x92\xA9\xFF";
92/// // An equivalent to '(?s-u:.)' is '(?-u:[\x00-\xFF])'.
93/// let re = Regex::new(r"(?s)(?-u:.)*?(?<f1>.+)(?-u:.)*?(?<f2>.+)").unwrap();
94/// let caps = re.captures(hay).unwrap();
95/// assert_eq!(&caps["f1"], &b"foo"[..]);
96/// assert_eq!(&caps["f2"], "💩".as_bytes());
97/// ```
98#[derive(Clone)]
99pub struct Regex {
100 pub(crate) meta: meta::Regex,
101 pub(crate) pattern: Arc<str>,
102}
103
104impl core::fmt::Display for Regex {
105 /// Shows the original regular expression.
106 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
107 write!(f, "{}", self.as_str())
108 }
109}
110
111impl core::fmt::Debug for Regex {
112 /// Shows the original regular expression.
113 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
114 f.debug_tuple(name:"Regex").field(&self.as_str()).finish()
115 }
116}
117
118impl core::str::FromStr for Regex {
119 type Err = Error;
120
121 /// Attempts to parse a string into a regular expression
122 fn from_str(s: &str) -> Result<Regex, Error> {
123 Regex::new(re:s)
124 }
125}
126
127impl TryFrom<&str> for Regex {
128 type Error = Error;
129
130 /// Attempts to parse a string into a regular expression
131 fn try_from(s: &str) -> Result<Regex, Error> {
132 Regex::new(re:s)
133 }
134}
135
136impl TryFrom<String> for Regex {
137 type Error = Error;
138
139 /// Attempts to parse a string into a regular expression
140 fn try_from(s: String) -> Result<Regex, Error> {
141 Regex::new(&s)
142 }
143}
144
145/// Core regular expression methods.
146impl Regex {
147 /// Compiles a regular expression. Once compiled, it can be used repeatedly
148 /// to search, split or replace substrings in a haystack.
149 ///
150 /// Note that regex compilation tends to be a somewhat expensive process,
151 /// and unlike higher level environments, compilation is not automatically
152 /// cached for you. One should endeavor to compile a regex once and then
153 /// reuse it. For example, it's a bad idea to compile the same regex
154 /// repeatedly in a loop.
155 ///
156 /// # Errors
157 ///
158 /// If an invalid pattern is given, then an error is returned.
159 /// An error is also returned if the pattern is valid, but would
160 /// produce a regex that is bigger than the configured size limit via
161 /// [`RegexBuilder::size_limit`]. (A reasonable size limit is enabled by
162 /// default.)
163 ///
164 /// # Example
165 ///
166 /// ```
167 /// use regex::bytes::Regex;
168 ///
169 /// // An Invalid pattern because of an unclosed parenthesis
170 /// assert!(Regex::new(r"foo(bar").is_err());
171 /// // An invalid pattern because the regex would be too big
172 /// // because Unicode tends to inflate things.
173 /// assert!(Regex::new(r"\w{1000}").is_err());
174 /// // Disabling Unicode can make the regex much smaller,
175 /// // potentially by up to or more than an order of magnitude.
176 /// assert!(Regex::new(r"(?-u:\w){1000}").is_ok());
177 /// ```
178 pub fn new(re: &str) -> Result<Regex, Error> {
179 RegexBuilder::new(re).build()
180 }
181
182 /// Returns true if and only if there is a match for the regex anywhere
183 /// in the haystack given.
184 ///
185 /// It is recommended to use this method if all you need to do is test
186 /// whether a match exists, since the underlying matching engine may be
187 /// able to do less work.
188 ///
189 /// # Example
190 ///
191 /// Test if some haystack contains at least one word with exactly 13
192 /// Unicode word characters:
193 ///
194 /// ```
195 /// use regex::bytes::Regex;
196 ///
197 /// let re = Regex::new(r"\b\w{13}\b").unwrap();
198 /// let hay = b"I categorically deny having triskaidekaphobia.";
199 /// assert!(re.is_match(hay));
200 /// ```
201 #[inline]
202 pub fn is_match(&self, haystack: &[u8]) -> bool {
203 self.is_match_at(haystack, 0)
204 }
205
206 /// This routine searches for the first match of this regex in the
207 /// haystack given, and if found, returns a [`Match`]. The `Match`
208 /// provides access to both the byte offsets of the match and the actual
209 /// substring that matched.
210 ///
211 /// Note that this should only be used if you want to find the entire
212 /// match. If instead you just want to test the existence of a match,
213 /// it's potentially faster to use `Regex::is_match(hay)` instead of
214 /// `Regex::find(hay).is_some()`.
215 ///
216 /// # Example
217 ///
218 /// Find the first word with exactly 13 Unicode word characters:
219 ///
220 /// ```
221 /// use regex::bytes::Regex;
222 ///
223 /// let re = Regex::new(r"\b\w{13}\b").unwrap();
224 /// let hay = b"I categorically deny having triskaidekaphobia.";
225 /// let mat = re.find(hay).unwrap();
226 /// assert_eq!(2..15, mat.range());
227 /// assert_eq!(b"categorically", mat.as_bytes());
228 /// ```
229 #[inline]
230 pub fn find<'h>(&self, haystack: &'h [u8]) -> Option<Match<'h>> {
231 self.find_at(haystack, 0)
232 }
233
234 /// Returns an iterator that yields successive non-overlapping matches in
235 /// the given haystack. The iterator yields values of type [`Match`].
236 ///
237 /// # Time complexity
238 ///
239 /// Note that since `find_iter` runs potentially many searches on the
240 /// haystack and since each search has worst case `O(m * n)` time
241 /// complexity, the overall worst case time complexity for iteration is
242 /// `O(m * n^2)`.
243 ///
244 /// # Example
245 ///
246 /// Find every word with exactly 13 Unicode word characters:
247 ///
248 /// ```
249 /// use regex::bytes::Regex;
250 ///
251 /// let re = Regex::new(r"\b\w{13}\b").unwrap();
252 /// let hay = b"Retroactively relinquishing remunerations is reprehensible.";
253 /// let matches: Vec<_> = re.find_iter(hay).map(|m| m.as_bytes()).collect();
254 /// assert_eq!(matches, vec![
255 /// &b"Retroactively"[..],
256 /// &b"relinquishing"[..],
257 /// &b"remunerations"[..],
258 /// &b"reprehensible"[..],
259 /// ]);
260 /// ```
261 #[inline]
262 pub fn find_iter<'r, 'h>(&'r self, haystack: &'h [u8]) -> Matches<'r, 'h> {
263 Matches { haystack, it: self.meta.find_iter(haystack) }
264 }
265
266 /// This routine searches for the first match of this regex in the haystack
267 /// given, and if found, returns not only the overall match but also the
268 /// matches of each capture group in the regex. If no match is found, then
269 /// `None` is returned.
270 ///
271 /// Capture group `0` always corresponds to an implicit unnamed group that
272 /// includes the entire match. If a match is found, this group is always
273 /// present. Subsequent groups may be named and are numbered, starting
274 /// at 1, by the order in which the opening parenthesis appears in the
275 /// pattern. For example, in the pattern `(?<a>.(?<b>.))(?<c>.)`, `a`,
276 /// `b` and `c` correspond to capture group indices `1`, `2` and `3`,
277 /// respectively.
278 ///
279 /// You should only use `captures` if you need access to the capture group
280 /// matches. Otherwise, [`Regex::find`] is generally faster for discovering
281 /// just the overall match.
282 ///
283 /// # Example
284 ///
285 /// Say you have some haystack with movie names and their release years,
286 /// like "'Citizen Kane' (1941)". It'd be nice if we could search for
287 /// strings looking like that, while also extracting the movie name and its
288 /// release year separately. The example below shows how to do that.
289 ///
290 /// ```
291 /// use regex::bytes::Regex;
292 ///
293 /// let re = Regex::new(r"'([^']+)'\s+\((\d{4})\)").unwrap();
294 /// let hay = b"Not my favorite movie: 'Citizen Kane' (1941).";
295 /// let caps = re.captures(hay).unwrap();
296 /// assert_eq!(caps.get(0).unwrap().as_bytes(), b"'Citizen Kane' (1941)");
297 /// assert_eq!(caps.get(1).unwrap().as_bytes(), b"Citizen Kane");
298 /// assert_eq!(caps.get(2).unwrap().as_bytes(), b"1941");
299 /// // You can also access the groups by index using the Index notation.
300 /// // Note that this will panic on an invalid index. In this case, these
301 /// // accesses are always correct because the overall regex will only
302 /// // match when these capture groups match.
303 /// assert_eq!(&caps[0], b"'Citizen Kane' (1941)");
304 /// assert_eq!(&caps[1], b"Citizen Kane");
305 /// assert_eq!(&caps[2], b"1941");
306 /// ```
307 ///
308 /// Note that the full match is at capture group `0`. Each subsequent
309 /// capture group is indexed by the order of its opening `(`.
310 ///
311 /// We can make this example a bit clearer by using *named* capture groups:
312 ///
313 /// ```
314 /// use regex::bytes::Regex;
315 ///
316 /// let re = Regex::new(r"'(?<title>[^']+)'\s+\((?<year>\d{4})\)").unwrap();
317 /// let hay = b"Not my favorite movie: 'Citizen Kane' (1941).";
318 /// let caps = re.captures(hay).unwrap();
319 /// assert_eq!(caps.get(0).unwrap().as_bytes(), b"'Citizen Kane' (1941)");
320 /// assert_eq!(caps.name("title").unwrap().as_bytes(), b"Citizen Kane");
321 /// assert_eq!(caps.name("year").unwrap().as_bytes(), b"1941");
322 /// // You can also access the groups by name using the Index notation.
323 /// // Note that this will panic on an invalid group name. In this case,
324 /// // these accesses are always correct because the overall regex will
325 /// // only match when these capture groups match.
326 /// assert_eq!(&caps[0], b"'Citizen Kane' (1941)");
327 /// assert_eq!(&caps["title"], b"Citizen Kane");
328 /// assert_eq!(&caps["year"], b"1941");
329 /// ```
330 ///
331 /// Here we name the capture groups, which we can access with the `name`
332 /// method or the `Index` notation with a `&str`. Note that the named
333 /// capture groups are still accessible with `get` or the `Index` notation
334 /// with a `usize`.
335 ///
336 /// The `0`th capture group is always unnamed, so it must always be
337 /// accessed with `get(0)` or `[0]`.
338 ///
339 /// Finally, one other way to to get the matched substrings is with the
340 /// [`Captures::extract`] API:
341 ///
342 /// ```
343 /// use regex::bytes::Regex;
344 ///
345 /// let re = Regex::new(r"'([^']+)'\s+\((\d{4})\)").unwrap();
346 /// let hay = b"Not my favorite movie: 'Citizen Kane' (1941).";
347 /// let (full, [title, year]) = re.captures(hay).unwrap().extract();
348 /// assert_eq!(full, b"'Citizen Kane' (1941)");
349 /// assert_eq!(title, b"Citizen Kane");
350 /// assert_eq!(year, b"1941");
351 /// ```
352 #[inline]
353 pub fn captures<'h>(&self, haystack: &'h [u8]) -> Option<Captures<'h>> {
354 self.captures_at(haystack, 0)
355 }
356
357 /// Returns an iterator that yields successive non-overlapping matches in
358 /// the given haystack. The iterator yields values of type [`Captures`].
359 ///
360 /// This is the same as [`Regex::find_iter`], but instead of only providing
361 /// access to the overall match, each value yield includes access to the
362 /// matches of all capture groups in the regex. Reporting this extra match
363 /// data is potentially costly, so callers should only use `captures_iter`
364 /// over `find_iter` when they actually need access to the capture group
365 /// matches.
366 ///
367 /// # Time complexity
368 ///
369 /// Note that since `captures_iter` runs potentially many searches on the
370 /// haystack and since each search has worst case `O(m * n)` time
371 /// complexity, the overall worst case time complexity for iteration is
372 /// `O(m * n^2)`.
373 ///
374 /// # Example
375 ///
376 /// We can use this to find all movie titles and their release years in
377 /// some haystack, where the movie is formatted like "'Title' (xxxx)":
378 ///
379 /// ```
380 /// use regex::bytes::Regex;
381 ///
382 /// let re = Regex::new(r"'([^']+)'\s+\(([0-9]{4})\)").unwrap();
383 /// let hay = b"'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931).";
384 /// let mut movies = vec![];
385 /// for (_, [title, year]) in re.captures_iter(hay).map(|c| c.extract()) {
386 /// // OK because [0-9]{4} can only match valid UTF-8.
387 /// let year = std::str::from_utf8(year).unwrap();
388 /// movies.push((title, year.parse::<i64>()?));
389 /// }
390 /// assert_eq!(movies, vec![
391 /// (&b"Citizen Kane"[..], 1941),
392 /// (&b"The Wizard of Oz"[..], 1939),
393 /// (&b"M"[..], 1931),
394 /// ]);
395 /// # Ok::<(), Box<dyn std::error::Error>>(())
396 /// ```
397 ///
398 /// Or with named groups:
399 ///
400 /// ```
401 /// use regex::bytes::Regex;
402 ///
403 /// let re = Regex::new(r"'(?<title>[^']+)'\s+\((?<year>[0-9]{4})\)").unwrap();
404 /// let hay = b"'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931).";
405 /// let mut it = re.captures_iter(hay);
406 ///
407 /// let caps = it.next().unwrap();
408 /// assert_eq!(&caps["title"], b"Citizen Kane");
409 /// assert_eq!(&caps["year"], b"1941");
410 ///
411 /// let caps = it.next().unwrap();
412 /// assert_eq!(&caps["title"], b"The Wizard of Oz");
413 /// assert_eq!(&caps["year"], b"1939");
414 ///
415 /// let caps = it.next().unwrap();
416 /// assert_eq!(&caps["title"], b"M");
417 /// assert_eq!(&caps["year"], b"1931");
418 /// ```
419 #[inline]
420 pub fn captures_iter<'r, 'h>(
421 &'r self,
422 haystack: &'h [u8],
423 ) -> CaptureMatches<'r, 'h> {
424 CaptureMatches { haystack, it: self.meta.captures_iter(haystack) }
425 }
426
427 /// Returns an iterator of substrings of the haystack given, delimited by a
428 /// match of the regex. Namely, each element of the iterator corresponds to
429 /// a part of the haystack that *isn't* matched by the regular expression.
430 ///
431 /// # Time complexity
432 ///
433 /// Since iterators over all matches requires running potentially many
434 /// searches on the haystack, and since each search has worst case
435 /// `O(m * n)` time complexity, the overall worst case time complexity for
436 /// this routine is `O(m * n^2)`.
437 ///
438 /// # Example
439 ///
440 /// To split a string delimited by arbitrary amounts of spaces or tabs:
441 ///
442 /// ```
443 /// use regex::bytes::Regex;
444 ///
445 /// let re = Regex::new(r"[ \t]+").unwrap();
446 /// let hay = b"a b \t c\td e";
447 /// let fields: Vec<&[u8]> = re.split(hay).collect();
448 /// assert_eq!(fields, vec![
449 /// &b"a"[..], &b"b"[..], &b"c"[..], &b"d"[..], &b"e"[..],
450 /// ]);
451 /// ```
452 ///
453 /// # Example: more cases
454 ///
455 /// Basic usage:
456 ///
457 /// ```
458 /// use regex::bytes::Regex;
459 ///
460 /// let re = Regex::new(r" ").unwrap();
461 /// let hay = b"Mary had a little lamb";
462 /// let got: Vec<&[u8]> = re.split(hay).collect();
463 /// assert_eq!(got, vec![
464 /// &b"Mary"[..], &b"had"[..], &b"a"[..], &b"little"[..], &b"lamb"[..],
465 /// ]);
466 ///
467 /// let re = Regex::new(r"X").unwrap();
468 /// let hay = b"";
469 /// let got: Vec<&[u8]> = re.split(hay).collect();
470 /// assert_eq!(got, vec![&b""[..]]);
471 ///
472 /// let re = Regex::new(r"X").unwrap();
473 /// let hay = b"lionXXtigerXleopard";
474 /// let got: Vec<&[u8]> = re.split(hay).collect();
475 /// assert_eq!(got, vec![
476 /// &b"lion"[..], &b""[..], &b"tiger"[..], &b"leopard"[..],
477 /// ]);
478 ///
479 /// let re = Regex::new(r"::").unwrap();
480 /// let hay = b"lion::tiger::leopard";
481 /// let got: Vec<&[u8]> = re.split(hay).collect();
482 /// assert_eq!(got, vec![&b"lion"[..], &b"tiger"[..], &b"leopard"[..]]);
483 /// ```
484 ///
485 /// If a haystack contains multiple contiguous matches, you will end up
486 /// with empty spans yielded by the iterator:
487 ///
488 /// ```
489 /// use regex::bytes::Regex;
490 ///
491 /// let re = Regex::new(r"X").unwrap();
492 /// let hay = b"XXXXaXXbXc";
493 /// let got: Vec<&[u8]> = re.split(hay).collect();
494 /// assert_eq!(got, vec![
495 /// &b""[..], &b""[..], &b""[..], &b""[..],
496 /// &b"a"[..], &b""[..], &b"b"[..], &b"c"[..],
497 /// ]);
498 ///
499 /// let re = Regex::new(r"/").unwrap();
500 /// let hay = b"(///)";
501 /// let got: Vec<&[u8]> = re.split(hay).collect();
502 /// assert_eq!(got, vec![&b"("[..], &b""[..], &b""[..], &b")"[..]]);
503 /// ```
504 ///
505 /// Separators at the start or end of a haystack are neighbored by empty
506 /// substring.
507 ///
508 /// ```
509 /// use regex::bytes::Regex;
510 ///
511 /// let re = Regex::new(r"0").unwrap();
512 /// let hay = b"010";
513 /// let got: Vec<&[u8]> = re.split(hay).collect();
514 /// assert_eq!(got, vec![&b""[..], &b"1"[..], &b""[..]]);
515 /// ```
516 ///
517 /// When the regex can match the empty string, it splits at every byte
518 /// position in the haystack. This includes between all UTF-8 code units.
519 /// (The top-level [`Regex::split`](crate::Regex::split) will only split
520 /// at valid UTF-8 boundaries.)
521 ///
522 /// ```
523 /// use regex::bytes::Regex;
524 ///
525 /// let re = Regex::new(r"").unwrap();
526 /// let hay = "☃".as_bytes();
527 /// let got: Vec<&[u8]> = re.split(hay).collect();
528 /// assert_eq!(got, vec![
529 /// &[][..], &[b'\xE2'][..], &[b'\x98'][..], &[b'\x83'][..], &[][..],
530 /// ]);
531 /// ```
532 ///
533 /// Contiguous separators (commonly shows up with whitespace), can lead to
534 /// possibly surprising behavior. For example, this code is correct:
535 ///
536 /// ```
537 /// use regex::bytes::Regex;
538 ///
539 /// let re = Regex::new(r" ").unwrap();
540 /// let hay = b" a b c";
541 /// let got: Vec<&[u8]> = re.split(hay).collect();
542 /// assert_eq!(got, vec![
543 /// &b""[..], &b""[..], &b""[..], &b""[..],
544 /// &b"a"[..], &b""[..], &b"b"[..], &b"c"[..],
545 /// ]);
546 /// ```
547 ///
548 /// It does *not* give you `["a", "b", "c"]`. For that behavior, you'd want
549 /// to match contiguous space characters:
550 ///
551 /// ```
552 /// use regex::bytes::Regex;
553 ///
554 /// let re = Regex::new(r" +").unwrap();
555 /// let hay = b" a b c";
556 /// let got: Vec<&[u8]> = re.split(hay).collect();
557 /// // N.B. This does still include a leading empty span because ' +'
558 /// // matches at the beginning of the haystack.
559 /// assert_eq!(got, vec![&b""[..], &b"a"[..], &b"b"[..], &b"c"[..]]);
560 /// ```
561 #[inline]
562 pub fn split<'r, 'h>(&'r self, haystack: &'h [u8]) -> Split<'r, 'h> {
563 Split { haystack, it: self.meta.split(haystack) }
564 }
565
566 /// Returns an iterator of at most `limit` substrings of the haystack
567 /// given, delimited by a match of the regex. (A `limit` of `0` will return
568 /// no substrings.) Namely, each element of the iterator corresponds to a
569 /// part of the haystack that *isn't* matched by the regular expression.
570 /// The remainder of the haystack that is not split will be the last
571 /// element in the iterator.
572 ///
573 /// # Time complexity
574 ///
575 /// Since iterators over all matches requires running potentially many
576 /// searches on the haystack, and since each search has worst case
577 /// `O(m * n)` time complexity, the overall worst case time complexity for
578 /// this routine is `O(m * n^2)`.
579 ///
580 /// Although note that the worst case time here has an upper bound given
581 /// by the `limit` parameter.
582 ///
583 /// # Example
584 ///
585 /// Get the first two words in some haystack:
586 ///
587 /// ```
588 /// use regex::bytes::Regex;
589 ///
590 /// let re = Regex::new(r"\W+").unwrap();
591 /// let hay = b"Hey! How are you?";
592 /// let fields: Vec<&[u8]> = re.splitn(hay, 3).collect();
593 /// assert_eq!(fields, vec![&b"Hey"[..], &b"How"[..], &b"are you?"[..]]);
594 /// ```
595 ///
596 /// # Examples: more cases
597 ///
598 /// ```
599 /// use regex::bytes::Regex;
600 ///
601 /// let re = Regex::new(r" ").unwrap();
602 /// let hay = b"Mary had a little lamb";
603 /// let got: Vec<&[u8]> = re.splitn(hay, 3).collect();
604 /// assert_eq!(got, vec![&b"Mary"[..], &b"had"[..], &b"a little lamb"[..]]);
605 ///
606 /// let re = Regex::new(r"X").unwrap();
607 /// let hay = b"";
608 /// let got: Vec<&[u8]> = re.splitn(hay, 3).collect();
609 /// assert_eq!(got, vec![&b""[..]]);
610 ///
611 /// let re = Regex::new(r"X").unwrap();
612 /// let hay = b"lionXXtigerXleopard";
613 /// let got: Vec<&[u8]> = re.splitn(hay, 3).collect();
614 /// assert_eq!(got, vec![&b"lion"[..], &b""[..], &b"tigerXleopard"[..]]);
615 ///
616 /// let re = Regex::new(r"::").unwrap();
617 /// let hay = b"lion::tiger::leopard";
618 /// let got: Vec<&[u8]> = re.splitn(hay, 2).collect();
619 /// assert_eq!(got, vec![&b"lion"[..], &b"tiger::leopard"[..]]);
620 ///
621 /// let re = Regex::new(r"X").unwrap();
622 /// let hay = b"abcXdef";
623 /// let got: Vec<&[u8]> = re.splitn(hay, 1).collect();
624 /// assert_eq!(got, vec![&b"abcXdef"[..]]);
625 ///
626 /// let re = Regex::new(r"X").unwrap();
627 /// let hay = b"abcdef";
628 /// let got: Vec<&[u8]> = re.splitn(hay, 2).collect();
629 /// assert_eq!(got, vec![&b"abcdef"[..]]);
630 ///
631 /// let re = Regex::new(r"X").unwrap();
632 /// let hay = b"abcXdef";
633 /// let got: Vec<&[u8]> = re.splitn(hay, 0).collect();
634 /// assert!(got.is_empty());
635 /// ```
636 #[inline]
637 pub fn splitn<'r, 'h>(
638 &'r self,
639 haystack: &'h [u8],
640 limit: usize,
641 ) -> SplitN<'r, 'h> {
642 SplitN { haystack, it: self.meta.splitn(haystack, limit) }
643 }
644
645 /// Replaces the leftmost-first match in the given haystack with the
646 /// replacement provided. The replacement can be a regular string (where
647 /// `$N` and `$name` are expanded to match capture groups) or a function
648 /// that takes a [`Captures`] and returns the replaced string.
649 ///
650 /// If no match is found, then the haystack is returned unchanged. In that
651 /// case, this implementation will likely return a `Cow::Borrowed` value
652 /// such that no allocation is performed.
653 ///
654 /// # Replacement string syntax
655 ///
656 /// All instances of `$ref` in the replacement string are replaced with
657 /// the substring corresponding to the capture group identified by `ref`.
658 ///
659 /// `ref` may be an integer corresponding to the index of the capture group
660 /// (counted by order of opening parenthesis where `0` is the entire match)
661 /// or it can be a name (consisting of letters, digits or underscores)
662 /// corresponding to a named capture group.
663 ///
664 /// If `ref` isn't a valid capture group (whether the name doesn't exist or
665 /// isn't a valid index), then it is replaced with the empty string.
666 ///
667 /// The longest possible name is used. For example, `$1a` looks up the
668 /// capture group named `1a` and not the capture group at index `1`. To
669 /// exert more precise control over the name, use braces, e.g., `${1}a`.
670 ///
671 /// To write a literal `$` use `$$`.
672 ///
673 /// # Example
674 ///
675 /// Note that this function is polymorphic with respect to the replacement.
676 /// In typical usage, this can just be a normal string:
677 ///
678 /// ```
679 /// use regex::bytes::Regex;
680 ///
681 /// let re = Regex::new(r"[^01]+").unwrap();
682 /// assert_eq!(re.replace(b"1078910", b""), &b"1010"[..]);
683 /// ```
684 ///
685 /// But anything satisfying the [`Replacer`] trait will work. For example,
686 /// a closure of type `|&Captures| -> String` provides direct access to the
687 /// captures corresponding to a match. This allows one to access capturing
688 /// group matches easily:
689 ///
690 /// ```
691 /// use regex::bytes::{Captures, Regex};
692 ///
693 /// let re = Regex::new(r"([^,\s]+),\s+(\S+)").unwrap();
694 /// let result = re.replace(b"Springsteen, Bruce", |caps: &Captures| {
695 /// let mut buf = vec![];
696 /// buf.extend_from_slice(&caps[2]);
697 /// buf.push(b' ');
698 /// buf.extend_from_slice(&caps[1]);
699 /// buf
700 /// });
701 /// assert_eq!(result, &b"Bruce Springsteen"[..]);
702 /// ```
703 ///
704 /// But this is a bit cumbersome to use all the time. Instead, a simple
705 /// syntax is supported (as described above) that expands `$name` into the
706 /// corresponding capture group. Here's the last example, but using this
707 /// expansion technique with named capture groups:
708 ///
709 /// ```
710 /// use regex::bytes::Regex;
711 ///
712 /// let re = Regex::new(r"(?<last>[^,\s]+),\s+(?<first>\S+)").unwrap();
713 /// let result = re.replace(b"Springsteen, Bruce", b"$first $last");
714 /// assert_eq!(result, &b"Bruce Springsteen"[..]);
715 /// ```
716 ///
717 /// Note that using `$2` instead of `$first` or `$1` instead of `$last`
718 /// would produce the same result. To write a literal `$` use `$$`.
719 ///
720 /// Sometimes the replacement string requires use of curly braces to
721 /// delineate a capture group replacement when it is adjacent to some other
722 /// literal text. For example, if we wanted to join two words together with
723 /// an underscore:
724 ///
725 /// ```
726 /// use regex::bytes::Regex;
727 ///
728 /// let re = Regex::new(r"(?<first>\w+)\s+(?<second>\w+)").unwrap();
729 /// let result = re.replace(b"deep fried", b"${first}_$second");
730 /// assert_eq!(result, &b"deep_fried"[..]);
731 /// ```
732 ///
733 /// Without the curly braces, the capture group name `first_` would be
734 /// used, and since it doesn't exist, it would be replaced with the empty
735 /// string.
736 ///
737 /// Finally, sometimes you just want to replace a literal string with no
738 /// regard for capturing group expansion. This can be done by wrapping a
739 /// string with [`NoExpand`]:
740 ///
741 /// ```
742 /// use regex::bytes::{NoExpand, Regex};
743 ///
744 /// let re = Regex::new(r"(?<last>[^,\s]+),\s+(\S+)").unwrap();
745 /// let result = re.replace(b"Springsteen, Bruce", NoExpand(b"$2 $last"));
746 /// assert_eq!(result, &b"$2 $last"[..]);
747 /// ```
748 ///
749 /// Using `NoExpand` may also be faster, since the replacement string won't
750 /// need to be parsed for the `$` syntax.
751 #[inline]
752 pub fn replace<'h, R: Replacer>(
753 &self,
754 haystack: &'h [u8],
755 rep: R,
756 ) -> Cow<'h, [u8]> {
757 self.replacen(haystack, 1, rep)
758 }
759
760 /// Replaces all non-overlapping matches in the haystack with the
761 /// replacement provided. This is the same as calling `replacen` with
762 /// `limit` set to `0`.
763 ///
764 /// The documentation for [`Regex::replace`] goes into more detail about
765 /// what kinds of replacement strings are supported.
766 ///
767 /// # Time complexity
768 ///
769 /// Since iterators over all matches requires running potentially many
770 /// searches on the haystack, and since each search has worst case
771 /// `O(m * n)` time complexity, the overall worst case time complexity for
772 /// this routine is `O(m * n^2)`.
773 ///
774 /// # Fallibility
775 ///
776 /// If you need to write a replacement routine where any individual
777 /// replacement might "fail," doing so with this API isn't really feasible
778 /// because there's no way to stop the search process if a replacement
779 /// fails. Instead, if you need this functionality, you should consider
780 /// implementing your own replacement routine:
781 ///
782 /// ```
783 /// use regex::bytes::{Captures, Regex};
784 ///
785 /// fn replace_all<E>(
786 /// re: &Regex,
787 /// haystack: &[u8],
788 /// replacement: impl Fn(&Captures) -> Result<Vec<u8>, E>,
789 /// ) -> Result<Vec<u8>, E> {
790 /// let mut new = Vec::with_capacity(haystack.len());
791 /// let mut last_match = 0;
792 /// for caps in re.captures_iter(haystack) {
793 /// let m = caps.get(0).unwrap();
794 /// new.extend_from_slice(&haystack[last_match..m.start()]);
795 /// new.extend_from_slice(&replacement(&caps)?);
796 /// last_match = m.end();
797 /// }
798 /// new.extend_from_slice(&haystack[last_match..]);
799 /// Ok(new)
800 /// }
801 ///
802 /// // Let's replace each word with the number of bytes in that word.
803 /// // But if we see a word that is "too long," we'll give up.
804 /// let re = Regex::new(r"\w+").unwrap();
805 /// let replacement = |caps: &Captures| -> Result<Vec<u8>, &'static str> {
806 /// if caps[0].len() >= 5 {
807 /// return Err("word too long");
808 /// }
809 /// Ok(caps[0].len().to_string().into_bytes())
810 /// };
811 /// assert_eq!(
812 /// Ok(b"2 3 3 3?".to_vec()),
813 /// replace_all(&re, b"hi how are you?", &replacement),
814 /// );
815 /// assert!(replace_all(&re, b"hi there", &replacement).is_err());
816 /// ```
817 ///
818 /// # Example
819 ///
820 /// This example shows how to flip the order of whitespace (excluding line
821 /// terminators) delimited fields, and normalizes the whitespace that
822 /// delimits the fields:
823 ///
824 /// ```
825 /// use regex::bytes::Regex;
826 ///
827 /// let re = Regex::new(r"(?m)^(\S+)[\s--\r\n]+(\S+)$").unwrap();
828 /// let hay = b"
829 /// Greetings 1973
830 /// Wild\t1973
831 /// BornToRun\t\t\t\t1975
832 /// Darkness 1978
833 /// TheRiver 1980
834 /// ";
835 /// let new = re.replace_all(hay, b"$2 $1");
836 /// assert_eq!(new, &b"
837 /// 1973 Greetings
838 /// 1973 Wild
839 /// 1975 BornToRun
840 /// 1978 Darkness
841 /// 1980 TheRiver
842 /// "[..]);
843 /// ```
844 #[inline]
845 pub fn replace_all<'h, R: Replacer>(
846 &self,
847 haystack: &'h [u8],
848 rep: R,
849 ) -> Cow<'h, [u8]> {
850 self.replacen(haystack, 0, rep)
851 }
852
853 /// Replaces at most `limit` non-overlapping matches in the haystack with
854 /// the replacement provided. If `limit` is `0`, then all non-overlapping
855 /// matches are replaced. That is, `Regex::replace_all(hay, rep)` is
856 /// equivalent to `Regex::replacen(hay, 0, rep)`.
857 ///
858 /// The documentation for [`Regex::replace`] goes into more detail about
859 /// what kinds of replacement strings are supported.
860 ///
861 /// # Time complexity
862 ///
863 /// Since iterators over all matches requires running potentially many
864 /// searches on the haystack, and since each search has worst case
865 /// `O(m * n)` time complexity, the overall worst case time complexity for
866 /// this routine is `O(m * n^2)`.
867 ///
868 /// Although note that the worst case time here has an upper bound given
869 /// by the `limit` parameter.
870 ///
871 /// # Fallibility
872 ///
873 /// See the corresponding section in the docs for [`Regex::replace_all`]
874 /// for tips on how to deal with a replacement routine that can fail.
875 ///
876 /// # Example
877 ///
878 /// This example shows how to flip the order of whitespace (excluding line
879 /// terminators) delimited fields, and normalizes the whitespace that
880 /// delimits the fields. But we only do it for the first two matches.
881 ///
882 /// ```
883 /// use regex::bytes::Regex;
884 ///
885 /// let re = Regex::new(r"(?m)^(\S+)[\s--\r\n]+(\S+)$").unwrap();
886 /// let hay = b"
887 /// Greetings 1973
888 /// Wild\t1973
889 /// BornToRun\t\t\t\t1975
890 /// Darkness 1978
891 /// TheRiver 1980
892 /// ";
893 /// let new = re.replacen(hay, 2, b"$2 $1");
894 /// assert_eq!(new, &b"
895 /// 1973 Greetings
896 /// 1973 Wild
897 /// BornToRun\t\t\t\t1975
898 /// Darkness 1978
899 /// TheRiver 1980
900 /// "[..]);
901 /// ```
902 #[inline]
903 pub fn replacen<'h, R: Replacer>(
904 &self,
905 haystack: &'h [u8],
906 limit: usize,
907 mut rep: R,
908 ) -> Cow<'h, [u8]> {
909 // If we know that the replacement doesn't have any capture expansions,
910 // then we can use the fast path. The fast path can make a tremendous
911 // difference:
912 //
913 // 1) We use `find_iter` instead of `captures_iter`. Not asking for
914 // captures generally makes the regex engines faster.
915 // 2) We don't need to look up all of the capture groups and do
916 // replacements inside the replacement string. We just push it
917 // at each match and be done with it.
918 if let Some(rep) = rep.no_expansion() {
919 let mut it = self.find_iter(haystack).enumerate().peekable();
920 if it.peek().is_none() {
921 return Cow::Borrowed(haystack);
922 }
923 let mut new = Vec::with_capacity(haystack.len());
924 let mut last_match = 0;
925 for (i, m) in it {
926 new.extend_from_slice(&haystack[last_match..m.start()]);
927 new.extend_from_slice(&rep);
928 last_match = m.end();
929 if limit > 0 && i >= limit - 1 {
930 break;
931 }
932 }
933 new.extend_from_slice(&haystack[last_match..]);
934 return Cow::Owned(new);
935 }
936
937 // The slower path, which we use if the replacement needs access to
938 // capture groups.
939 let mut it = self.captures_iter(haystack).enumerate().peekable();
940 if it.peek().is_none() {
941 return Cow::Borrowed(haystack);
942 }
943 let mut new = Vec::with_capacity(haystack.len());
944 let mut last_match = 0;
945 for (i, cap) in it {
946 // unwrap on 0 is OK because captures only reports matches
947 let m = cap.get(0).unwrap();
948 new.extend_from_slice(&haystack[last_match..m.start()]);
949 rep.replace_append(&cap, &mut new);
950 last_match = m.end();
951 if limit > 0 && i >= limit - 1 {
952 break;
953 }
954 }
955 new.extend_from_slice(&haystack[last_match..]);
956 Cow::Owned(new)
957 }
958}
959
960/// A group of advanced or "lower level" search methods. Some methods permit
961/// starting the search at a position greater than `0` in the haystack. Other
962/// methods permit reusing allocations, for example, when extracting the
963/// matches for capture groups.
964impl Regex {
965 /// Returns the end byte offset of the first match in the haystack given.
966 ///
967 /// This method may have the same performance characteristics as
968 /// `is_match`. Behaviorlly, it doesn't just report whether it match
969 /// occurs, but also the end offset for a match. In particular, the offset
970 /// returned *may be shorter* than the proper end of the leftmost-first
971 /// match that you would find via [`Regex::find`].
972 ///
973 /// Note that it is not guaranteed that this routine finds the shortest or
974 /// "earliest" possible match. Instead, the main idea of this API is that
975 /// it returns the offset at the point at which the internal regex engine
976 /// has determined that a match has occurred. This may vary depending on
977 /// which internal regex engine is used, and thus, the offset itself may
978 /// change based on internal heuristics.
979 ///
980 /// # Example
981 ///
982 /// Typically, `a+` would match the entire first sequence of `a` in some
983 /// haystack, but `shortest_match` *may* give up as soon as it sees the
984 /// first `a`.
985 ///
986 /// ```
987 /// use regex::bytes::Regex;
988 ///
989 /// let re = Regex::new(r"a+").unwrap();
990 /// let offset = re.shortest_match(b"aaaaa").unwrap();
991 /// assert_eq!(offset, 1);
992 /// ```
993 #[inline]
994 pub fn shortest_match(&self, haystack: &[u8]) -> Option<usize> {
995 self.shortest_match_at(haystack, 0)
996 }
997
998 /// Returns the same as `shortest_match`, but starts the search at the
999 /// given offset.
1000 ///
1001 /// The significance of the starting point is that it takes the surrounding
1002 /// context into consideration. For example, the `\A` anchor can only match
1003 /// when `start == 0`.
1004 ///
1005 /// If a match is found, the offset returned is relative to the beginning
1006 /// of the haystack, not the beginning of the search.
1007 ///
1008 /// # Panics
1009 ///
1010 /// This panics when `start >= haystack.len() + 1`.
1011 ///
1012 /// # Example
1013 ///
1014 /// This example shows the significance of `start` by demonstrating how it
1015 /// can be used to permit look-around assertions in a regex to take the
1016 /// surrounding context into account.
1017 ///
1018 /// ```
1019 /// use regex::bytes::Regex;
1020 ///
1021 /// let re = Regex::new(r"\bchew\b").unwrap();
1022 /// let hay = b"eschew";
1023 /// // We get a match here, but it's probably not intended.
1024 /// assert_eq!(re.shortest_match(&hay[2..]), Some(4));
1025 /// // No match because the assertions take the context into account.
1026 /// assert_eq!(re.shortest_match_at(hay, 2), None);
1027 /// ```
1028 #[inline]
1029 pub fn shortest_match_at(
1030 &self,
1031 haystack: &[u8],
1032 start: usize,
1033 ) -> Option<usize> {
1034 let input =
1035 Input::new(haystack).earliest(true).span(start..haystack.len());
1036 self.meta.search_half(&input).map(|hm| hm.offset())
1037 }
1038
1039 /// Returns the same as [`Regex::is_match`], but starts the search at the
1040 /// given offset.
1041 ///
1042 /// The significance of the starting point is that it takes the surrounding
1043 /// context into consideration. For example, the `\A` anchor can only
1044 /// match when `start == 0`.
1045 ///
1046 /// # Panics
1047 ///
1048 /// This panics when `start >= haystack.len() + 1`.
1049 ///
1050 /// # Example
1051 ///
1052 /// This example shows the significance of `start` by demonstrating how it
1053 /// can be used to permit look-around assertions in a regex to take the
1054 /// surrounding context into account.
1055 ///
1056 /// ```
1057 /// use regex::bytes::Regex;
1058 ///
1059 /// let re = Regex::new(r"\bchew\b").unwrap();
1060 /// let hay = b"eschew";
1061 /// // We get a match here, but it's probably not intended.
1062 /// assert!(re.is_match(&hay[2..]));
1063 /// // No match because the assertions take the context into account.
1064 /// assert!(!re.is_match_at(hay, 2));
1065 /// ```
1066 #[inline]
1067 pub fn is_match_at(&self, haystack: &[u8], start: usize) -> bool {
1068 self.meta.is_match(Input::new(haystack).span(start..haystack.len()))
1069 }
1070
1071 /// Returns the same as [`Regex::find`], but starts the search at the given
1072 /// offset.
1073 ///
1074 /// The significance of the starting point is that it takes the surrounding
1075 /// context into consideration. For example, the `\A` anchor can only
1076 /// match when `start == 0`.
1077 ///
1078 /// # Panics
1079 ///
1080 /// This panics when `start >= haystack.len() + 1`.
1081 ///
1082 /// # Example
1083 ///
1084 /// This example shows the significance of `start` by demonstrating how it
1085 /// can be used to permit look-around assertions in a regex to take the
1086 /// surrounding context into account.
1087 ///
1088 /// ```
1089 /// use regex::bytes::Regex;
1090 ///
1091 /// let re = Regex::new(r"\bchew\b").unwrap();
1092 /// let hay = b"eschew";
1093 /// // We get a match here, but it's probably not intended.
1094 /// assert_eq!(re.find(&hay[2..]).map(|m| m.range()), Some(0..4));
1095 /// // No match because the assertions take the context into account.
1096 /// assert_eq!(re.find_at(hay, 2), None);
1097 /// ```
1098 #[inline]
1099 pub fn find_at<'h>(
1100 &self,
1101 haystack: &'h [u8],
1102 start: usize,
1103 ) -> Option<Match<'h>> {
1104 let input = Input::new(haystack).span(start..haystack.len());
1105 self.meta.find(input).map(|m| Match::new(haystack, m.start(), m.end()))
1106 }
1107
1108 /// Returns the same as [`Regex::captures`], but starts the search at the
1109 /// given offset.
1110 ///
1111 /// The significance of the starting point is that it takes the surrounding
1112 /// context into consideration. For example, the `\A` anchor can only
1113 /// match when `start == 0`.
1114 ///
1115 /// # Panics
1116 ///
1117 /// This panics when `start >= haystack.len() + 1`.
1118 ///
1119 /// # Example
1120 ///
1121 /// This example shows the significance of `start` by demonstrating how it
1122 /// can be used to permit look-around assertions in a regex to take the
1123 /// surrounding context into account.
1124 ///
1125 /// ```
1126 /// use regex::bytes::Regex;
1127 ///
1128 /// let re = Regex::new(r"\bchew\b").unwrap();
1129 /// let hay = b"eschew";
1130 /// // We get a match here, but it's probably not intended.
1131 /// assert_eq!(&re.captures(&hay[2..]).unwrap()[0], b"chew");
1132 /// // No match because the assertions take the context into account.
1133 /// assert!(re.captures_at(hay, 2).is_none());
1134 /// ```
1135 #[inline]
1136 pub fn captures_at<'h>(
1137 &self,
1138 haystack: &'h [u8],
1139 start: usize,
1140 ) -> Option<Captures<'h>> {
1141 let input = Input::new(haystack).span(start..haystack.len());
1142 let mut caps = self.meta.create_captures();
1143 self.meta.captures(input, &mut caps);
1144 if caps.is_match() {
1145 let static_captures_len = self.static_captures_len();
1146 Some(Captures { haystack, caps, static_captures_len })
1147 } else {
1148 None
1149 }
1150 }
1151
1152 /// This is like [`Regex::captures`], but writes the byte offsets of each
1153 /// capture group match into the locations given.
1154 ///
1155 /// A [`CaptureLocations`] stores the same byte offsets as a [`Captures`],
1156 /// but does *not* store a reference to the haystack. This makes its API
1157 /// a bit lower level and less convenient. But in exchange, callers
1158 /// may allocate their own `CaptureLocations` and reuse it for multiple
1159 /// searches. This may be helpful if allocating a `Captures` shows up in a
1160 /// profile as too costly.
1161 ///
1162 /// To create a `CaptureLocations` value, use the
1163 /// [`Regex::capture_locations`] method.
1164 ///
1165 /// This also returns the overall match if one was found. When a match is
1166 /// found, its offsets are also always stored in `locs` at index `0`.
1167 ///
1168 /// # Example
1169 ///
1170 /// ```
1171 /// use regex::bytes::Regex;
1172 ///
1173 /// let re = Regex::new(r"^([a-z]+)=(\S*)$").unwrap();
1174 /// let mut locs = re.capture_locations();
1175 /// assert!(re.captures_read(&mut locs, b"id=foo123").is_some());
1176 /// assert_eq!(Some((0, 9)), locs.get(0));
1177 /// assert_eq!(Some((0, 2)), locs.get(1));
1178 /// assert_eq!(Some((3, 9)), locs.get(2));
1179 /// ```
1180 #[inline]
1181 pub fn captures_read<'h>(
1182 &self,
1183 locs: &mut CaptureLocations,
1184 haystack: &'h [u8],
1185 ) -> Option<Match<'h>> {
1186 self.captures_read_at(locs, haystack, 0)
1187 }
1188
1189 /// Returns the same as [`Regex::captures_read`], but starts the search at
1190 /// the given offset.
1191 ///
1192 /// The significance of the starting point is that it takes the surrounding
1193 /// context into consideration. For example, the `\A` anchor can only
1194 /// match when `start == 0`.
1195 ///
1196 /// # Panics
1197 ///
1198 /// This panics when `start >= haystack.len() + 1`.
1199 ///
1200 /// # Example
1201 ///
1202 /// This example shows the significance of `start` by demonstrating how it
1203 /// can be used to permit look-around assertions in a regex to take the
1204 /// surrounding context into account.
1205 ///
1206 /// ```
1207 /// use regex::bytes::Regex;
1208 ///
1209 /// let re = Regex::new(r"\bchew\b").unwrap();
1210 /// let hay = b"eschew";
1211 /// let mut locs = re.capture_locations();
1212 /// // We get a match here, but it's probably not intended.
1213 /// assert!(re.captures_read(&mut locs, &hay[2..]).is_some());
1214 /// // No match because the assertions take the context into account.
1215 /// assert!(re.captures_read_at(&mut locs, hay, 2).is_none());
1216 /// ```
1217 #[inline]
1218 pub fn captures_read_at<'h>(
1219 &self,
1220 locs: &mut CaptureLocations,
1221 haystack: &'h [u8],
1222 start: usize,
1223 ) -> Option<Match<'h>> {
1224 let input = Input::new(haystack).span(start..haystack.len());
1225 self.meta.search_captures(&input, &mut locs.0);
1226 locs.0.get_match().map(|m| Match::new(haystack, m.start(), m.end()))
1227 }
1228
1229 /// An undocumented alias for `captures_read_at`.
1230 ///
1231 /// The `regex-capi` crate previously used this routine, so to avoid
1232 /// breaking that crate, we continue to provide the name as an undocumented
1233 /// alias.
1234 #[doc(hidden)]
1235 #[inline]
1236 pub fn read_captures_at<'h>(
1237 &self,
1238 locs: &mut CaptureLocations,
1239 haystack: &'h [u8],
1240 start: usize,
1241 ) -> Option<Match<'h>> {
1242 self.captures_read_at(locs, haystack, start)
1243 }
1244}
1245
1246/// Auxiliary methods.
1247impl Regex {
1248 /// Returns the original string of this regex.
1249 ///
1250 /// # Example
1251 ///
1252 /// ```
1253 /// use regex::bytes::Regex;
1254 ///
1255 /// let re = Regex::new(r"foo\w+bar").unwrap();
1256 /// assert_eq!(re.as_str(), r"foo\w+bar");
1257 /// ```
1258 #[inline]
1259 pub fn as_str(&self) -> &str {
1260 &self.pattern
1261 }
1262
1263 /// Returns an iterator over the capture names in this regex.
1264 ///
1265 /// The iterator returned yields elements of type `Option<&str>`. That is,
1266 /// the iterator yields values for all capture groups, even ones that are
1267 /// unnamed. The order of the groups corresponds to the order of the group's
1268 /// corresponding opening parenthesis.
1269 ///
1270 /// The first element of the iterator always yields the group corresponding
1271 /// to the overall match, and this group is always unnamed. Therefore, the
1272 /// iterator always yields at least one group.
1273 ///
1274 /// # Example
1275 ///
1276 /// This shows basic usage with a mix of named and unnamed capture groups:
1277 ///
1278 /// ```
1279 /// use regex::bytes::Regex;
1280 ///
1281 /// let re = Regex::new(r"(?<a>.(?<b>.))(.)(?:.)(?<c>.)").unwrap();
1282 /// let mut names = re.capture_names();
1283 /// assert_eq!(names.next(), Some(None));
1284 /// assert_eq!(names.next(), Some(Some("a")));
1285 /// assert_eq!(names.next(), Some(Some("b")));
1286 /// assert_eq!(names.next(), Some(None));
1287 /// // the '(?:.)' group is non-capturing and so doesn't appear here!
1288 /// assert_eq!(names.next(), Some(Some("c")));
1289 /// assert_eq!(names.next(), None);
1290 /// ```
1291 ///
1292 /// The iterator always yields at least one element, even for regexes with
1293 /// no capture groups and even for regexes that can never match:
1294 ///
1295 /// ```
1296 /// use regex::bytes::Regex;
1297 ///
1298 /// let re = Regex::new(r"").unwrap();
1299 /// let mut names = re.capture_names();
1300 /// assert_eq!(names.next(), Some(None));
1301 /// assert_eq!(names.next(), None);
1302 ///
1303 /// let re = Regex::new(r"[a&&b]").unwrap();
1304 /// let mut names = re.capture_names();
1305 /// assert_eq!(names.next(), Some(None));
1306 /// assert_eq!(names.next(), None);
1307 /// ```
1308 #[inline]
1309 pub fn capture_names(&self) -> CaptureNames<'_> {
1310 CaptureNames(self.meta.group_info().pattern_names(PatternID::ZERO))
1311 }
1312
1313 /// Returns the number of captures groups in this regex.
1314 ///
1315 /// This includes all named and unnamed groups, including the implicit
1316 /// unnamed group that is always present and corresponds to the entire
1317 /// match.
1318 ///
1319 /// Since the implicit unnamed group is always included in this length, the
1320 /// length returned is guaranteed to be greater than zero.
1321 ///
1322 /// # Example
1323 ///
1324 /// ```
1325 /// use regex::bytes::Regex;
1326 ///
1327 /// let re = Regex::new(r"foo").unwrap();
1328 /// assert_eq!(1, re.captures_len());
1329 ///
1330 /// let re = Regex::new(r"(foo)").unwrap();
1331 /// assert_eq!(2, re.captures_len());
1332 ///
1333 /// let re = Regex::new(r"(?<a>.(?<b>.))(.)(?:.)(?<c>.)").unwrap();
1334 /// assert_eq!(5, re.captures_len());
1335 ///
1336 /// let re = Regex::new(r"[a&&b]").unwrap();
1337 /// assert_eq!(1, re.captures_len());
1338 /// ```
1339 #[inline]
1340 pub fn captures_len(&self) -> usize {
1341 self.meta.group_info().group_len(PatternID::ZERO)
1342 }
1343
1344 /// Returns the total number of capturing groups that appear in every
1345 /// possible match.
1346 ///
1347 /// If the number of capture groups can vary depending on the match, then
1348 /// this returns `None`. That is, a value is only returned when the number
1349 /// of matching groups is invariant or "static."
1350 ///
1351 /// Note that like [`Regex::captures_len`], this **does** include the
1352 /// implicit capturing group corresponding to the entire match. Therefore,
1353 /// when a non-None value is returned, it is guaranteed to be at least `1`.
1354 /// Stated differently, a return value of `Some(0)` is impossible.
1355 ///
1356 /// # Example
1357 ///
1358 /// This shows a few cases where a static number of capture groups is
1359 /// available and a few cases where it is not.
1360 ///
1361 /// ```
1362 /// use regex::bytes::Regex;
1363 ///
1364 /// let len = |pattern| {
1365 /// Regex::new(pattern).map(|re| re.static_captures_len())
1366 /// };
1367 ///
1368 /// assert_eq!(Some(1), len("a")?);
1369 /// assert_eq!(Some(2), len("(a)")?);
1370 /// assert_eq!(Some(2), len("(a)|(b)")?);
1371 /// assert_eq!(Some(3), len("(a)(b)|(c)(d)")?);
1372 /// assert_eq!(None, len("(a)|b")?);
1373 /// assert_eq!(None, len("a|(b)")?);
1374 /// assert_eq!(None, len("(b)*")?);
1375 /// assert_eq!(Some(2), len("(b)+")?);
1376 ///
1377 /// # Ok::<(), Box<dyn std::error::Error>>(())
1378 /// ```
1379 #[inline]
1380 pub fn static_captures_len(&self) -> Option<usize> {
1381 self.meta.static_captures_len()
1382 }
1383
1384 /// Returns a fresh allocated set of capture locations that can
1385 /// be reused in multiple calls to [`Regex::captures_read`] or
1386 /// [`Regex::captures_read_at`].
1387 ///
1388 /// # Example
1389 ///
1390 /// ```
1391 /// use regex::bytes::Regex;
1392 ///
1393 /// let re = Regex::new(r"(.)(.)(\w+)").unwrap();
1394 /// let mut locs = re.capture_locations();
1395 /// assert!(re.captures_read(&mut locs, b"Padron").is_some());
1396 /// assert_eq!(locs.get(0), Some((0, 6)));
1397 /// assert_eq!(locs.get(1), Some((0, 1)));
1398 /// assert_eq!(locs.get(2), Some((1, 2)));
1399 /// assert_eq!(locs.get(3), Some((2, 6)));
1400 /// ```
1401 #[inline]
1402 pub fn capture_locations(&self) -> CaptureLocations {
1403 CaptureLocations(self.meta.create_captures())
1404 }
1405
1406 /// An alias for `capture_locations` to preserve backward compatibility.
1407 ///
1408 /// The `regex-capi` crate uses this method, so to avoid breaking that
1409 /// crate, we continue to export it as an undocumented API.
1410 #[doc(hidden)]
1411 #[inline]
1412 pub fn locations(&self) -> CaptureLocations {
1413 self.capture_locations()
1414 }
1415}
1416
1417/// Represents a single match of a regex in a haystack.
1418///
1419/// A `Match` contains both the start and end byte offsets of the match and the
1420/// actual substring corresponding to the range of those byte offsets. It is
1421/// guaranteed that `start <= end`. When `start == end`, the match is empty.
1422///
1423/// Unlike the top-level `Match` type, this `Match` type is produced by APIs
1424/// that search `&[u8]` haystacks. This means that the offsets in a `Match` can
1425/// point to anywhere in the haystack, including in a place that splits the
1426/// UTF-8 encoding of a Unicode scalar value.
1427///
1428/// The lifetime parameter `'h` refers to the lifetime of the matched of the
1429/// haystack that this match was produced from.
1430///
1431/// # Numbering
1432///
1433/// The byte offsets in a `Match` form a half-open interval. That is, the
1434/// start of the range is inclusive and the end of the range is exclusive.
1435/// For example, given a haystack `abcFOOxyz` and a match of `FOO`, its byte
1436/// offset range starts at `3` and ends at `6`. `3` corresponds to `F` and
1437/// `6` corresponds to `x`, which is one past the end of the match. This
1438/// corresponds to the same kind of slicing that Rust uses.
1439///
1440/// For more on why this was chosen over other schemes (aside from being
1441/// consistent with how Rust the language works), see [this discussion] and
1442/// [Dijkstra's note on a related topic][note].
1443///
1444/// [this discussion]: https://github.com/rust-lang/regex/discussions/866
1445/// [note]: https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html
1446///
1447/// # Example
1448///
1449/// This example shows the value of each of the methods on `Match` for a
1450/// particular search.
1451///
1452/// ```
1453/// use regex::bytes::Regex;
1454///
1455/// let re = Regex::new(r"\p{Greek}+").unwrap();
1456/// let hay = "Greek: αβγδ".as_bytes();
1457/// let m = re.find(hay).unwrap();
1458/// assert_eq!(7, m.start());
1459/// assert_eq!(15, m.end());
1460/// assert!(!m.is_empty());
1461/// assert_eq!(8, m.len());
1462/// assert_eq!(7..15, m.range());
1463/// assert_eq!("αβγδ".as_bytes(), m.as_bytes());
1464/// ```
1465#[derive(Copy, Clone, Eq, PartialEq)]
1466pub struct Match<'h> {
1467 haystack: &'h [u8],
1468 start: usize,
1469 end: usize,
1470}
1471
1472impl<'h> Match<'h> {
1473 /// Returns the byte offset of the start of the match in the haystack. The
1474 /// start of the match corresponds to the position where the match begins
1475 /// and includes the first byte in the match.
1476 ///
1477 /// It is guaranteed that `Match::start() <= Match::end()`.
1478 ///
1479 /// Unlike the top-level `Match` type, the start offset may appear anywhere
1480 /// in the haystack. This includes between the code units of a UTF-8
1481 /// encoded Unicode scalar value.
1482 #[inline]
1483 pub fn start(&self) -> usize {
1484 self.start
1485 }
1486
1487 /// Returns the byte offset of the end of the match in the haystack. The
1488 /// end of the match corresponds to the byte immediately following the last
1489 /// byte in the match. This means that `&slice[start..end]` works as one
1490 /// would expect.
1491 ///
1492 /// It is guaranteed that `Match::start() <= Match::end()`.
1493 ///
1494 /// Unlike the top-level `Match` type, the start offset may appear anywhere
1495 /// in the haystack. This includes between the code units of a UTF-8
1496 /// encoded Unicode scalar value.
1497 #[inline]
1498 pub fn end(&self) -> usize {
1499 self.end
1500 }
1501
1502 /// Returns true if and only if this match has a length of zero.
1503 ///
1504 /// Note that an empty match can only occur when the regex itself can
1505 /// match the empty string. Here are some examples of regexes that can
1506 /// all match the empty string: `^`, `^$`, `\b`, `a?`, `a*`, `a{0}`,
1507 /// `(foo|\d+|quux)?`.
1508 #[inline]
1509 pub fn is_empty(&self) -> bool {
1510 self.start == self.end
1511 }
1512
1513 /// Returns the length, in bytes, of this match.
1514 #[inline]
1515 pub fn len(&self) -> usize {
1516 self.end - self.start
1517 }
1518
1519 /// Returns the range over the starting and ending byte offsets of the
1520 /// match in the haystack.
1521 #[inline]
1522 pub fn range(&self) -> core::ops::Range<usize> {
1523 self.start..self.end
1524 }
1525
1526 /// Returns the substring of the haystack that matched.
1527 #[inline]
1528 pub fn as_bytes(&self) -> &'h [u8] {
1529 &self.haystack[self.range()]
1530 }
1531
1532 /// Creates a new match from the given haystack and byte offsets.
1533 #[inline]
1534 fn new(haystack: &'h [u8], start: usize, end: usize) -> Match<'h> {
1535 Match { haystack, start, end }
1536 }
1537}
1538
1539impl<'h> core::fmt::Debug for Match<'h> {
1540 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1541 let mut fmt: DebugStruct<'_, '_> = f.debug_struct(name:"Match");
1542 fmt.field("start", &self.start).field(name:"end", &self.end);
1543 if let Ok(s: &str) = core::str::from_utf8(self.as_bytes()) {
1544 fmt.field(name:"bytes", &s);
1545 } else {
1546 // FIXME: It would be nice if this could be printed as a string
1547 // with invalid UTF-8 replaced with hex escapes. A alloc would
1548 // probably okay if that makes it easier, but regex-automata does
1549 // (at time of writing) have internal routines that do this. So
1550 // maybe we should expose them.
1551 fmt.field(name:"bytes", &self.as_bytes());
1552 }
1553 fmt.finish()
1554 }
1555}
1556
1557impl<'h> From<Match<'h>> for &'h [u8] {
1558 fn from(m: Match<'h>) -> &'h [u8] {
1559 m.as_bytes()
1560 }
1561}
1562
1563impl<'h> From<Match<'h>> for core::ops::Range<usize> {
1564 fn from(m: Match<'h>) -> core::ops::Range<usize> {
1565 m.range()
1566 }
1567}
1568
1569/// Represents the capture groups for a single match.
1570///
1571/// Capture groups refer to parts of a regex enclosed in parentheses. They
1572/// can be optionally named. The purpose of capture groups is to be able to
1573/// reference different parts of a match based on the original pattern. In
1574/// essence, a `Captures` is a container of [`Match`] values for each group
1575/// that participated in a regex match. Each `Match` can be looked up by either
1576/// its capture group index or name (if it has one).
1577///
1578/// For example, say you want to match the individual letters in a 5-letter
1579/// word:
1580///
1581/// ```text
1582/// (?<first>\w)(\w)(?:\w)\w(?<last>\w)
1583/// ```
1584///
1585/// This regex has 4 capture groups:
1586///
1587/// * The group at index `0` corresponds to the overall match. It is always
1588/// present in every match and never has a name.
1589/// * The group at index `1` with name `first` corresponding to the first
1590/// letter.
1591/// * The group at index `2` with no name corresponding to the second letter.
1592/// * The group at index `3` with name `last` corresponding to the fifth and
1593/// last letter.
1594///
1595/// Notice that `(?:\w)` was not listed above as a capture group despite it
1596/// being enclosed in parentheses. That's because `(?:pattern)` is a special
1597/// syntax that permits grouping but *without* capturing. The reason for not
1598/// treating it as a capture is that tracking and reporting capture groups
1599/// requires additional state that may lead to slower searches. So using as few
1600/// capture groups as possible can help performance. (Although the difference
1601/// in performance of a couple of capture groups is likely immaterial.)
1602///
1603/// Values with this type are created by [`Regex::captures`] or
1604/// [`Regex::captures_iter`].
1605///
1606/// `'h` is the lifetime of the haystack that these captures were matched from.
1607///
1608/// # Example
1609///
1610/// ```
1611/// use regex::bytes::Regex;
1612///
1613/// let re = Regex::new(r"(?<first>\w)(\w)(?:\w)\w(?<last>\w)").unwrap();
1614/// let caps = re.captures(b"toady").unwrap();
1615/// assert_eq!(b"toady", &caps[0]);
1616/// assert_eq!(b"t", &caps["first"]);
1617/// assert_eq!(b"o", &caps[2]);
1618/// assert_eq!(b"y", &caps["last"]);
1619/// ```
1620pub struct Captures<'h> {
1621 haystack: &'h [u8],
1622 caps: captures::Captures,
1623 static_captures_len: Option<usize>,
1624}
1625
1626impl<'h> Captures<'h> {
1627 /// Returns the `Match` associated with the capture group at index `i`. If
1628 /// `i` does not correspond to a capture group, or if the capture group did
1629 /// not participate in the match, then `None` is returned.
1630 ///
1631 /// When `i == 0`, this is guaranteed to return a non-`None` value.
1632 ///
1633 /// # Examples
1634 ///
1635 /// Get the substring that matched with a default of an empty string if the
1636 /// group didn't participate in the match:
1637 ///
1638 /// ```
1639 /// use regex::bytes::Regex;
1640 ///
1641 /// let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap();
1642 /// let caps = re.captures(b"abc123").unwrap();
1643 ///
1644 /// let substr1 = caps.get(1).map_or(&b""[..], |m| m.as_bytes());
1645 /// let substr2 = caps.get(2).map_or(&b""[..], |m| m.as_bytes());
1646 /// assert_eq!(substr1, b"123");
1647 /// assert_eq!(substr2, b"");
1648 /// ```
1649 #[inline]
1650 pub fn get(&self, i: usize) -> Option<Match<'h>> {
1651 self.caps
1652 .get_group(i)
1653 .map(|sp| Match::new(self.haystack, sp.start, sp.end))
1654 }
1655
1656 /// Returns the `Match` associated with the capture group named `name`. If
1657 /// `name` isn't a valid capture group or it refers to a group that didn't
1658 /// match, then `None` is returned.
1659 ///
1660 /// Note that unlike `caps["name"]`, this returns a `Match` whose lifetime
1661 /// matches the lifetime of the haystack in this `Captures` value.
1662 /// Conversely, the substring returned by `caps["name"]` has a lifetime
1663 /// of the `Captures` value, which is likely shorter than the lifetime of
1664 /// the haystack. In some cases, it may be necessary to use this method to
1665 /// access the matching substring instead of the `caps["name"]` notation.
1666 ///
1667 /// # Examples
1668 ///
1669 /// Get the substring that matched with a default of an empty string if the
1670 /// group didn't participate in the match:
1671 ///
1672 /// ```
1673 /// use regex::bytes::Regex;
1674 ///
1675 /// let re = Regex::new(
1676 /// r"[a-z]+(?:(?<numbers>[0-9]+)|(?<letters>[A-Z]+))",
1677 /// ).unwrap();
1678 /// let caps = re.captures(b"abc123").unwrap();
1679 ///
1680 /// let numbers = caps.name("numbers").map_or(&b""[..], |m| m.as_bytes());
1681 /// let letters = caps.name("letters").map_or(&b""[..], |m| m.as_bytes());
1682 /// assert_eq!(numbers, b"123");
1683 /// assert_eq!(letters, b"");
1684 /// ```
1685 #[inline]
1686 pub fn name(&self, name: &str) -> Option<Match<'h>> {
1687 self.caps
1688 .get_group_by_name(name)
1689 .map(|sp| Match::new(self.haystack, sp.start, sp.end))
1690 }
1691
1692 /// This is a convenience routine for extracting the substrings
1693 /// corresponding to matching capture groups.
1694 ///
1695 /// This returns a tuple where the first element corresponds to the full
1696 /// substring of the haystack that matched the regex. The second element is
1697 /// an array of substrings, with each corresponding to the to the substring
1698 /// that matched for a particular capture group.
1699 ///
1700 /// # Panics
1701 ///
1702 /// This panics if the number of possible matching groups in this
1703 /// `Captures` value is not fixed to `N` in all circumstances.
1704 /// More precisely, this routine only works when `N` is equivalent to
1705 /// [`Regex::static_captures_len`].
1706 ///
1707 /// Stated more plainly, if the number of matching capture groups in a
1708 /// regex can vary from match to match, then this function always panics.
1709 ///
1710 /// For example, `(a)(b)|(c)` could produce two matching capture groups
1711 /// or one matching capture group for any given match. Therefore, one
1712 /// cannot use `extract` with such a pattern.
1713 ///
1714 /// But a pattern like `(a)(b)|(c)(d)` can be used with `extract` because
1715 /// the number of capture groups in every match is always equivalent,
1716 /// even if the capture _indices_ in each match are not.
1717 ///
1718 /// # Example
1719 ///
1720 /// ```
1721 /// use regex::bytes::Regex;
1722 ///
1723 /// let re = Regex::new(r"([0-9]{4})-([0-9]{2})-([0-9]{2})").unwrap();
1724 /// let hay = b"On 2010-03-14, I became a Tenneessee lamb.";
1725 /// let Some((full, [year, month, day])) =
1726 /// re.captures(hay).map(|caps| caps.extract()) else { return };
1727 /// assert_eq!(b"2010-03-14", full);
1728 /// assert_eq!(b"2010", year);
1729 /// assert_eq!(b"03", month);
1730 /// assert_eq!(b"14", day);
1731 /// ```
1732 ///
1733 /// # Example: iteration
1734 ///
1735 /// This example shows how to use this method when iterating over all
1736 /// `Captures` matches in a haystack.
1737 ///
1738 /// ```
1739 /// use regex::bytes::Regex;
1740 ///
1741 /// let re = Regex::new(r"([0-9]{4})-([0-9]{2})-([0-9]{2})").unwrap();
1742 /// let hay = b"1973-01-05, 1975-08-25 and 1980-10-18";
1743 ///
1744 /// let mut dates: Vec<(&[u8], &[u8], &[u8])> = vec![];
1745 /// for (_, [y, m, d]) in re.captures_iter(hay).map(|c| c.extract()) {
1746 /// dates.push((y, m, d));
1747 /// }
1748 /// assert_eq!(dates, vec![
1749 /// (&b"1973"[..], &b"01"[..], &b"05"[..]),
1750 /// (&b"1975"[..], &b"08"[..], &b"25"[..]),
1751 /// (&b"1980"[..], &b"10"[..], &b"18"[..]),
1752 /// ]);
1753 /// ```
1754 ///
1755 /// # Example: parsing different formats
1756 ///
1757 /// This API is particularly useful when you need to extract a particular
1758 /// value that might occur in a different format. Consider, for example,
1759 /// an identifier that might be in double quotes or single quotes:
1760 ///
1761 /// ```
1762 /// use regex::bytes::Regex;
1763 ///
1764 /// let re = Regex::new(r#"id:(?:"([^"]+)"|'([^']+)')"#).unwrap();
1765 /// let hay = br#"The first is id:"foo" and the second is id:'bar'."#;
1766 /// let mut ids = vec![];
1767 /// for (_, [id]) in re.captures_iter(hay).map(|c| c.extract()) {
1768 /// ids.push(id);
1769 /// }
1770 /// assert_eq!(ids, vec![b"foo", b"bar"]);
1771 /// ```
1772 pub fn extract<const N: usize>(&self) -> (&'h [u8], [&'h [u8]; N]) {
1773 let len = self
1774 .static_captures_len
1775 .expect("number of capture groups can vary in a match")
1776 .checked_sub(1)
1777 .expect("number of groups is always greater than zero");
1778 assert_eq!(N, len, "asked for {} groups, but must ask for {}", N, len);
1779 // The regex-automata variant of extract is a bit more permissive.
1780 // It doesn't require the number of matching capturing groups to be
1781 // static, and you can even request fewer groups than what's there. So
1782 // this is guaranteed to never panic because we've asserted above that
1783 // the user has requested precisely the number of groups that must be
1784 // present in any match for this regex.
1785 self.caps.extract_bytes(self.haystack)
1786 }
1787
1788 /// Expands all instances of `$ref` in `replacement` to the corresponding
1789 /// capture group, and writes them to the `dst` buffer given. A `ref` can
1790 /// be a capture group index or a name. If `ref` doesn't refer to a capture
1791 /// group that participated in the match, then it is replaced with the
1792 /// empty string.
1793 ///
1794 /// # Format
1795 ///
1796 /// The format of the replacement string supports two different kinds of
1797 /// capture references: unbraced and braced.
1798 ///
1799 /// For the unbraced format, the format supported is `$ref` where `name`
1800 /// can be any character in the class `[0-9A-Za-z_]`. `ref` is always
1801 /// the longest possible parse. So for example, `$1a` corresponds to the
1802 /// capture group named `1a` and not the capture group at index `1`. If
1803 /// `ref` matches `^[0-9]+$`, then it is treated as a capture group index
1804 /// itself and not a name.
1805 ///
1806 /// For the braced format, the format supported is `${ref}` where `ref` can
1807 /// be any sequence of bytes except for `}`. If no closing brace occurs,
1808 /// then it is not considered a capture reference. As with the unbraced
1809 /// format, if `ref` matches `^[0-9]+$`, then it is treated as a capture
1810 /// group index and not a name.
1811 ///
1812 /// The braced format is useful for exerting precise control over the name
1813 /// of the capture reference. For example, `${1}a` corresponds to the
1814 /// capture group reference `1` followed by the letter `a`, where as `$1a`
1815 /// (as mentioned above) corresponds to the capture group reference `1a`.
1816 /// The braced format is also useful for expressing capture group names
1817 /// that use characters not supported by the unbraced format. For example,
1818 /// `${foo[bar].baz}` refers to the capture group named `foo[bar].baz`.
1819 ///
1820 /// If a capture group reference is found and it does not refer to a valid
1821 /// capture group, then it will be replaced with the empty string.
1822 ///
1823 /// To write a literal `$`, use `$$`.
1824 ///
1825 /// # Example
1826 ///
1827 /// ```
1828 /// use regex::bytes::Regex;
1829 ///
1830 /// let re = Regex::new(
1831 /// r"(?<day>[0-9]{2})-(?<month>[0-9]{2})-(?<year>[0-9]{4})",
1832 /// ).unwrap();
1833 /// let hay = b"On 14-03-2010, I became a Tenneessee lamb.";
1834 /// let caps = re.captures(hay).unwrap();
1835 ///
1836 /// let mut dst = vec![];
1837 /// caps.expand(b"year=$year, month=$month, day=$day", &mut dst);
1838 /// assert_eq!(dst, b"year=2010, month=03, day=14");
1839 /// ```
1840 #[inline]
1841 pub fn expand(&self, replacement: &[u8], dst: &mut Vec<u8>) {
1842 self.caps.interpolate_bytes_into(self.haystack, replacement, dst);
1843 }
1844
1845 /// Returns an iterator over all capture groups. This includes both
1846 /// matching and non-matching groups.
1847 ///
1848 /// The iterator always yields at least one matching group: the first group
1849 /// (at index `0`) with no name. Subsequent groups are returned in the order
1850 /// of their opening parenthesis in the regex.
1851 ///
1852 /// The elements yielded have type `Option<Match<'h>>`, where a non-`None`
1853 /// value is present if the capture group matches.
1854 ///
1855 /// # Example
1856 ///
1857 /// ```
1858 /// use regex::bytes::Regex;
1859 ///
1860 /// let re = Regex::new(r"(\w)(\d)?(\w)").unwrap();
1861 /// let caps = re.captures(b"AZ").unwrap();
1862 ///
1863 /// let mut it = caps.iter();
1864 /// assert_eq!(it.next().unwrap().map(|m| m.as_bytes()), Some(&b"AZ"[..]));
1865 /// assert_eq!(it.next().unwrap().map(|m| m.as_bytes()), Some(&b"A"[..]));
1866 /// assert_eq!(it.next().unwrap().map(|m| m.as_bytes()), None);
1867 /// assert_eq!(it.next().unwrap().map(|m| m.as_bytes()), Some(&b"Z"[..]));
1868 /// assert_eq!(it.next(), None);
1869 /// ```
1870 #[inline]
1871 pub fn iter<'c>(&'c self) -> SubCaptureMatches<'c, 'h> {
1872 SubCaptureMatches { haystack: self.haystack, it: self.caps.iter() }
1873 }
1874
1875 /// Returns the total number of capture groups. This includes both
1876 /// matching and non-matching groups.
1877 ///
1878 /// The length returned is always equivalent to the number of elements
1879 /// yielded by [`Captures::iter`]. Consequently, the length is always
1880 /// greater than zero since every `Captures` value always includes the
1881 /// match for the entire regex.
1882 ///
1883 /// # Example
1884 ///
1885 /// ```
1886 /// use regex::bytes::Regex;
1887 ///
1888 /// let re = Regex::new(r"(\w)(\d)?(\w)").unwrap();
1889 /// let caps = re.captures(b"AZ").unwrap();
1890 /// assert_eq!(caps.len(), 4);
1891 /// ```
1892 #[inline]
1893 pub fn len(&self) -> usize {
1894 self.caps.group_len()
1895 }
1896}
1897
1898impl<'h> core::fmt::Debug for Captures<'h> {
1899 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1900 /// A little helper type to provide a nice map-like debug
1901 /// representation for our capturing group spans.
1902 ///
1903 /// regex-automata has something similar, but it includes the pattern
1904 /// ID in its debug output, which is confusing. It also doesn't include
1905 /// that strings that match because a regex-automata `Captures` doesn't
1906 /// borrow the haystack.
1907 struct CapturesDebugMap<'a> {
1908 caps: &'a Captures<'a>,
1909 }
1910
1911 impl<'a> core::fmt::Debug for CapturesDebugMap<'a> {
1912 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1913 let mut map = f.debug_map();
1914 let names =
1915 self.caps.caps.group_info().pattern_names(PatternID::ZERO);
1916 for (group_index, maybe_name) in names.enumerate() {
1917 let key = Key(group_index, maybe_name);
1918 match self.caps.get(group_index) {
1919 None => map.entry(&key, &None::<()>),
1920 Some(mat) => map.entry(&key, &Value(mat)),
1921 };
1922 }
1923 map.finish()
1924 }
1925 }
1926
1927 struct Key<'a>(usize, Option<&'a str>);
1928
1929 impl<'a> core::fmt::Debug for Key<'a> {
1930 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1931 write!(f, "{}", self.0)?;
1932 if let Some(name) = self.1 {
1933 write!(f, "/{:?}", name)?;
1934 }
1935 Ok(())
1936 }
1937 }
1938
1939 struct Value<'a>(Match<'a>);
1940
1941 impl<'a> core::fmt::Debug for Value<'a> {
1942 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1943 use regex_automata::util::escape::DebugHaystack;
1944
1945 write!(
1946 f,
1947 "{}..{}/{:?}",
1948 self.0.start(),
1949 self.0.end(),
1950 DebugHaystack(self.0.as_bytes())
1951 )
1952 }
1953 }
1954
1955 f.debug_tuple("Captures")
1956 .field(&CapturesDebugMap { caps: self })
1957 .finish()
1958 }
1959}
1960
1961/// Get a matching capture group's haystack substring by index.
1962///
1963/// The haystack substring returned can't outlive the `Captures` object if this
1964/// method is used, because of how `Index` is defined (normally `a[i]` is part
1965/// of `a` and can't outlive it). To work around this limitation, do that, use
1966/// [`Captures::get`] instead.
1967///
1968/// `'h` is the lifetime of the matched haystack, but the lifetime of the
1969/// `&str` returned by this implementation is the lifetime of the `Captures`
1970/// value itself.
1971///
1972/// # Panics
1973///
1974/// If there is no matching group at the given index.
1975impl<'h> core::ops::Index<usize> for Captures<'h> {
1976 type Output = [u8];
1977
1978 // The lifetime is written out to make it clear that the &str returned
1979 // does NOT have a lifetime equivalent to 'h.
1980 fn index<'a>(&'a self, i: usize) -> &'a [u8] {
1981 self.get(i)
1982 .map(|m: Match<'_>| m.as_bytes())
1983 .unwrap_or_else(|| panic!("no group at index '{}'", i))
1984 }
1985}
1986
1987/// Get a matching capture group's haystack substring by name.
1988///
1989/// The haystack substring returned can't outlive the `Captures` object if this
1990/// method is used, because of how `Index` is defined (normally `a[i]` is part
1991/// of `a` and can't outlive it). To work around this limitation, do that, use
1992/// [`Captures::name`] instead.
1993///
1994/// `'h` is the lifetime of the matched haystack, but the lifetime of the
1995/// `&str` returned by this implementation is the lifetime of the `Captures`
1996/// value itself.
1997///
1998/// `'n` is the lifetime of the group name used to index the `Captures` value.
1999///
2000/// # Panics
2001///
2002/// If there is no matching group at the given name.
2003impl<'h, 'n> core::ops::Index<&'n str> for Captures<'h> {
2004 type Output = [u8];
2005
2006 fn index<'a>(&'a self, name: &'n str) -> &'a [u8] {
2007 self.name(name)
2008 .map(|m: Match<'_>| m.as_bytes())
2009 .unwrap_or_else(|| panic!("no group named '{}'", name))
2010 }
2011}
2012
2013/// A low level representation of the byte offsets of each capture group.
2014///
2015/// You can think of this as a lower level [`Captures`], where this type does
2016/// not support named capturing groups directly and it does not borrow the
2017/// haystack that these offsets were matched on.
2018///
2019/// Primarily, this type is useful when using the lower level `Regex` APIs such
2020/// as [`Regex::captures_read`], which permits amortizing the allocation in
2021/// which capture match offsets are stored.
2022///
2023/// In order to build a value of this type, you'll need to call the
2024/// [`Regex::capture_locations`] method. The value returned can then be reused
2025/// in subsequent searches for that regex. Using it for other regexes may
2026/// result in a panic or otherwise incorrect results.
2027///
2028/// # Example
2029///
2030/// This example shows how to create and use `CaptureLocations` in a search.
2031///
2032/// ```
2033/// use regex::bytes::Regex;
2034///
2035/// let re = Regex::new(r"(?<first>\w+)\s+(?<last>\w+)").unwrap();
2036/// let mut locs = re.capture_locations();
2037/// let m = re.captures_read(&mut locs, b"Bruce Springsteen").unwrap();
2038/// assert_eq!(0..17, m.range());
2039/// assert_eq!(Some((0, 17)), locs.get(0));
2040/// assert_eq!(Some((0, 5)), locs.get(1));
2041/// assert_eq!(Some((6, 17)), locs.get(2));
2042///
2043/// // Asking for an invalid capture group always returns None.
2044/// assert_eq!(None, locs.get(3));
2045/// # // literals are too big for 32-bit usize: #1041
2046/// # #[cfg(target_pointer_width = "64")]
2047/// assert_eq!(None, locs.get(34973498648));
2048/// # #[cfg(target_pointer_width = "64")]
2049/// assert_eq!(None, locs.get(9944060567225171988));
2050/// ```
2051#[derive(Clone, Debug)]
2052pub struct CaptureLocations(captures::Captures);
2053
2054/// A type alias for `CaptureLocations` for backwards compatibility.
2055///
2056/// Previously, we exported `CaptureLocations` as `Locations` in an
2057/// undocumented API. To prevent breaking that code (e.g., in `regex-capi`),
2058/// we continue re-exporting the same undocumented API.
2059#[doc(hidden)]
2060pub type Locations = CaptureLocations;
2061
2062impl CaptureLocations {
2063 /// Returns the start and end byte offsets of the capture group at index
2064 /// `i`. This returns `None` if `i` is not a valid capture group or if the
2065 /// capture group did not match.
2066 ///
2067 /// # Example
2068 ///
2069 /// ```
2070 /// use regex::bytes::Regex;
2071 ///
2072 /// let re = Regex::new(r"(?<first>\w+)\s+(?<last>\w+)").unwrap();
2073 /// let mut locs = re.capture_locations();
2074 /// re.captures_read(&mut locs, b"Bruce Springsteen").unwrap();
2075 /// assert_eq!(Some((0, 17)), locs.get(0));
2076 /// assert_eq!(Some((0, 5)), locs.get(1));
2077 /// assert_eq!(Some((6, 17)), locs.get(2));
2078 /// ```
2079 #[inline]
2080 pub fn get(&self, i: usize) -> Option<(usize, usize)> {
2081 self.0.get_group(i).map(|sp| (sp.start, sp.end))
2082 }
2083
2084 /// Returns the total number of capture groups (even if they didn't match).
2085 /// That is, the length returned is unaffected by the result of a search.
2086 ///
2087 /// This is always at least `1` since every regex has at least `1`
2088 /// capturing group that corresponds to the entire match.
2089 ///
2090 /// # Example
2091 ///
2092 /// ```
2093 /// use regex::bytes::Regex;
2094 ///
2095 /// let re = Regex::new(r"(?<first>\w+)\s+(?<last>\w+)").unwrap();
2096 /// let mut locs = re.capture_locations();
2097 /// assert_eq!(3, locs.len());
2098 /// re.captures_read(&mut locs, b"Bruce Springsteen").unwrap();
2099 /// assert_eq!(3, locs.len());
2100 /// ```
2101 ///
2102 /// Notice that the length is always at least `1`, regardless of the regex:
2103 ///
2104 /// ```
2105 /// use regex::bytes::Regex;
2106 ///
2107 /// let re = Regex::new(r"").unwrap();
2108 /// let locs = re.capture_locations();
2109 /// assert_eq!(1, locs.len());
2110 ///
2111 /// // [a&&b] is a regex that never matches anything.
2112 /// let re = Regex::new(r"[a&&b]").unwrap();
2113 /// let locs = re.capture_locations();
2114 /// assert_eq!(1, locs.len());
2115 /// ```
2116 #[inline]
2117 pub fn len(&self) -> usize {
2118 // self.0.group_len() returns 0 if the underlying captures doesn't
2119 // represent a match, but the behavior guaranteed for this method is
2120 // that the length doesn't change based on a match or not.
2121 self.0.group_info().group_len(PatternID::ZERO)
2122 }
2123
2124 /// An alias for the `get` method for backwards compatibility.
2125 ///
2126 /// Previously, we exported `get` as `pos` in an undocumented API. To
2127 /// prevent breaking that code (e.g., in `regex-capi`), we continue
2128 /// re-exporting the same undocumented API.
2129 #[doc(hidden)]
2130 #[inline]
2131 pub fn pos(&self, i: usize) -> Option<(usize, usize)> {
2132 self.get(i)
2133 }
2134}
2135
2136/// An iterator over all non-overlapping matches in a haystack.
2137///
2138/// This iterator yields [`Match`] values. The iterator stops when no more
2139/// matches can be found.
2140///
2141/// `'r` is the lifetime of the compiled regular expression and `'h` is the
2142/// lifetime of the haystack.
2143///
2144/// This iterator is created by [`Regex::find_iter`].
2145///
2146/// # Time complexity
2147///
2148/// Note that since an iterator runs potentially many searches on the haystack
2149/// and since each search has worst case `O(m * n)` time complexity, the
2150/// overall worst case time complexity for iteration is `O(m * n^2)`.
2151#[derive(Debug)]
2152pub struct Matches<'r, 'h> {
2153 haystack: &'h [u8],
2154 it: meta::FindMatches<'r, 'h>,
2155}
2156
2157impl<'r, 'h> Iterator for Matches<'r, 'h> {
2158 type Item = Match<'h>;
2159
2160 #[inline]
2161 fn next(&mut self) -> Option<Match<'h>> {
2162 self.it
2163 .next()
2164 .map(|sp: Match| Match::new(self.haystack, sp.start(), sp.end()))
2165 }
2166
2167 #[inline]
2168 fn count(self) -> usize {
2169 // This can actually be up to 2x faster than calling `next()` until
2170 // completion, because counting matches when using a DFA only requires
2171 // finding the end of each match. But returning a `Match` via `next()`
2172 // requires the start of each match which, with a DFA, requires a
2173 // reverse forward scan to find it.
2174 self.it.count()
2175 }
2176}
2177
2178impl<'r, 'h> core::iter::FusedIterator for Matches<'r, 'h> {}
2179
2180/// An iterator over all non-overlapping capture matches in a haystack.
2181///
2182/// This iterator yields [`Captures`] values. The iterator stops when no more
2183/// matches can be found.
2184///
2185/// `'r` is the lifetime of the compiled regular expression and `'h` is the
2186/// lifetime of the matched string.
2187///
2188/// This iterator is created by [`Regex::captures_iter`].
2189///
2190/// # Time complexity
2191///
2192/// Note that since an iterator runs potentially many searches on the haystack
2193/// and since each search has worst case `O(m * n)` time complexity, the
2194/// overall worst case time complexity for iteration is `O(m * n^2)`.
2195#[derive(Debug)]
2196pub struct CaptureMatches<'r, 'h> {
2197 haystack: &'h [u8],
2198 it: meta::CapturesMatches<'r, 'h>,
2199}
2200
2201impl<'r, 'h> Iterator for CaptureMatches<'r, 'h> {
2202 type Item = Captures<'h>;
2203
2204 #[inline]
2205 fn next(&mut self) -> Option<Captures<'h>> {
2206 let static_captures_len: Option = self.it.regex().static_captures_len();
2207 self.it.next().map(|caps: Captures| Captures {
2208 haystack: self.haystack,
2209 caps,
2210 static_captures_len,
2211 })
2212 }
2213
2214 #[inline]
2215 fn count(self) -> usize {
2216 // This can actually be up to 2x faster than calling `next()` until
2217 // completion, because counting matches when using a DFA only requires
2218 // finding the end of each match. But returning a `Match` via `next()`
2219 // requires the start of each match which, with a DFA, requires a
2220 // reverse forward scan to find it.
2221 self.it.count()
2222 }
2223}
2224
2225impl<'r, 'h> core::iter::FusedIterator for CaptureMatches<'r, 'h> {}
2226
2227/// An iterator over all substrings delimited by a regex match.
2228///
2229/// `'r` is the lifetime of the compiled regular expression and `'h` is the
2230/// lifetime of the byte string being split.
2231///
2232/// This iterator is created by [`Regex::split`].
2233///
2234/// # Time complexity
2235///
2236/// Note that since an iterator runs potentially many searches on the haystack
2237/// and since each search has worst case `O(m * n)` time complexity, the
2238/// overall worst case time complexity for iteration is `O(m * n^2)`.
2239#[derive(Debug)]
2240pub struct Split<'r, 'h> {
2241 haystack: &'h [u8],
2242 it: meta::Split<'r, 'h>,
2243}
2244
2245impl<'r, 'h> Iterator for Split<'r, 'h> {
2246 type Item = &'h [u8];
2247
2248 #[inline]
2249 fn next(&mut self) -> Option<&'h [u8]> {
2250 self.it.next().map(|span: Span| &self.haystack[span])
2251 }
2252}
2253
2254impl<'r, 'h> core::iter::FusedIterator for Split<'r, 'h> {}
2255
2256/// An iterator over at most `N` substrings delimited by a regex match.
2257///
2258/// The last substring yielded by this iterator will be whatever remains after
2259/// `N-1` splits.
2260///
2261/// `'r` is the lifetime of the compiled regular expression and `'h` is the
2262/// lifetime of the byte string being split.
2263///
2264/// This iterator is created by [`Regex::splitn`].
2265///
2266/// # Time complexity
2267///
2268/// Note that since an iterator runs potentially many searches on the haystack
2269/// and since each search has worst case `O(m * n)` time complexity, the
2270/// overall worst case time complexity for iteration is `O(m * n^2)`.
2271///
2272/// Although note that the worst case time here has an upper bound given
2273/// by the `limit` parameter to [`Regex::splitn`].
2274#[derive(Debug)]
2275pub struct SplitN<'r, 'h> {
2276 haystack: &'h [u8],
2277 it: meta::SplitN<'r, 'h>,
2278}
2279
2280impl<'r, 'h> Iterator for SplitN<'r, 'h> {
2281 type Item = &'h [u8];
2282
2283 #[inline]
2284 fn next(&mut self) -> Option<&'h [u8]> {
2285 self.it.next().map(|span: Span| &self.haystack[span])
2286 }
2287
2288 #[inline]
2289 fn size_hint(&self) -> (usize, Option<usize>) {
2290 self.it.size_hint()
2291 }
2292}
2293
2294impl<'r, 'h> core::iter::FusedIterator for SplitN<'r, 'h> {}
2295
2296/// An iterator over the names of all capture groups in a regex.
2297///
2298/// This iterator yields values of type `Option<&str>` in order of the opening
2299/// capture group parenthesis in the regex pattern. `None` is yielded for
2300/// groups with no name. The first element always corresponds to the implicit
2301/// and unnamed group for the overall match.
2302///
2303/// `'r` is the lifetime of the compiled regular expression.
2304///
2305/// This iterator is created by [`Regex::capture_names`].
2306#[derive(Clone, Debug)]
2307pub struct CaptureNames<'r>(captures::GroupInfoPatternNames<'r>);
2308
2309impl<'r> Iterator for CaptureNames<'r> {
2310 type Item = Option<&'r str>;
2311
2312 #[inline]
2313 fn next(&mut self) -> Option<Option<&'r str>> {
2314 self.0.next()
2315 }
2316
2317 #[inline]
2318 fn size_hint(&self) -> (usize, Option<usize>) {
2319 self.0.size_hint()
2320 }
2321
2322 #[inline]
2323 fn count(self) -> usize {
2324 self.0.count()
2325 }
2326}
2327
2328impl<'r> ExactSizeIterator for CaptureNames<'r> {}
2329
2330impl<'r> core::iter::FusedIterator for CaptureNames<'r> {}
2331
2332/// An iterator over all group matches in a [`Captures`] value.
2333///
2334/// This iterator yields values of type `Option<Match<'h>>`, where `'h` is the
2335/// lifetime of the haystack that the matches are for. The order of elements
2336/// yielded corresponds to the order of the opening parenthesis for the group
2337/// in the regex pattern. `None` is yielded for groups that did not participate
2338/// in the match.
2339///
2340/// The first element always corresponds to the implicit group for the overall
2341/// match. Since this iterator is created by a [`Captures`] value, and a
2342/// `Captures` value is only created when a match occurs, it follows that the
2343/// first element yielded by this iterator is guaranteed to be non-`None`.
2344///
2345/// The lifetime `'c` corresponds to the lifetime of the `Captures` value that
2346/// created this iterator, and the lifetime `'h` corresponds to the originally
2347/// matched haystack.
2348#[derive(Clone, Debug)]
2349pub struct SubCaptureMatches<'c, 'h> {
2350 haystack: &'h [u8],
2351 it: captures::CapturesPatternIter<'c>,
2352}
2353
2354impl<'c, 'h> Iterator for SubCaptureMatches<'c, 'h> {
2355 type Item = Option<Match<'h>>;
2356
2357 #[inline]
2358 fn next(&mut self) -> Option<Option<Match<'h>>> {
2359 self.it.next().map(|group: Option| {
2360 group.map(|sp: Span| Match::new(self.haystack, sp.start, sp.end))
2361 })
2362 }
2363
2364 #[inline]
2365 fn size_hint(&self) -> (usize, Option<usize>) {
2366 self.it.size_hint()
2367 }
2368
2369 #[inline]
2370 fn count(self) -> usize {
2371 self.it.count()
2372 }
2373}
2374
2375impl<'c, 'h> ExactSizeIterator for SubCaptureMatches<'c, 'h> {}
2376
2377impl<'c, 'h> core::iter::FusedIterator for SubCaptureMatches<'c, 'h> {}
2378
2379/// A trait for types that can be used to replace matches in a haystack.
2380///
2381/// In general, users of this crate shouldn't need to implement this trait,
2382/// since implementations are already provided for `&[u8]` along with other
2383/// variants of byte string types, as well as `FnMut(&Captures) -> Vec<u8>` (or
2384/// any `FnMut(&Captures) -> T` where `T: AsRef<[u8]>`). Those cover most use
2385/// cases, but callers can implement this trait directly if necessary.
2386///
2387/// # Example
2388///
2389/// This example shows a basic implementation of the `Replacer` trait. This can
2390/// be done much more simply using the replacement byte string interpolation
2391/// support (e.g., `$first $last`), but this approach avoids needing to parse
2392/// the replacement byte string at all.
2393///
2394/// ```
2395/// use regex::bytes::{Captures, Regex, Replacer};
2396///
2397/// struct NameSwapper;
2398///
2399/// impl Replacer for NameSwapper {
2400/// fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2401/// dst.extend_from_slice(&caps["first"]);
2402/// dst.extend_from_slice(b" ");
2403/// dst.extend_from_slice(&caps["last"]);
2404/// }
2405/// }
2406///
2407/// let re = Regex::new(r"(?<last>[^,\s]+),\s+(?<first>\S+)").unwrap();
2408/// let result = re.replace(b"Springsteen, Bruce", NameSwapper);
2409/// assert_eq!(result, &b"Bruce Springsteen"[..]);
2410/// ```
2411pub trait Replacer {
2412 /// Appends possibly empty data to `dst` to replace the current match.
2413 ///
2414 /// The current match is represented by `caps`, which is guaranteed to have
2415 /// a match at capture group `0`.
2416 ///
2417 /// For example, a no-op replacement would be
2418 /// `dst.extend_from_slice(&caps[0])`.
2419 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>);
2420
2421 /// Return a fixed unchanging replacement byte string.
2422 ///
2423 /// When doing replacements, if access to [`Captures`] is not needed (e.g.,
2424 /// the replacement byte string does not need `$` expansion), then it can
2425 /// be beneficial to avoid finding sub-captures.
2426 ///
2427 /// In general, this is called once for every call to a replacement routine
2428 /// such as [`Regex::replace_all`].
2429 fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, [u8]>> {
2430 None
2431 }
2432
2433 /// Returns a type that implements `Replacer`, but that borrows and wraps
2434 /// this `Replacer`.
2435 ///
2436 /// This is useful when you want to take a generic `Replacer` (which might
2437 /// not be cloneable) and use it without consuming it, so it can be used
2438 /// more than once.
2439 ///
2440 /// # Example
2441 ///
2442 /// ```
2443 /// use regex::bytes::{Regex, Replacer};
2444 ///
2445 /// fn replace_all_twice<R: Replacer>(
2446 /// re: Regex,
2447 /// src: &[u8],
2448 /// mut rep: R,
2449 /// ) -> Vec<u8> {
2450 /// let dst = re.replace_all(src, rep.by_ref());
2451 /// let dst = re.replace_all(&dst, rep.by_ref());
2452 /// dst.into_owned()
2453 /// }
2454 /// ```
2455 fn by_ref<'r>(&'r mut self) -> ReplacerRef<'r, Self> {
2456 ReplacerRef(self)
2457 }
2458}
2459
2460impl<'a, const N: usize> Replacer for &'a [u8; N] {
2461 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2462 caps.expand(&**self, dst);
2463 }
2464
2465 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2466 no_expansion(self)
2467 }
2468}
2469
2470impl<const N: usize> Replacer for [u8; N] {
2471 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2472 caps.expand(&*self, dst);
2473 }
2474
2475 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2476 no_expansion(self)
2477 }
2478}
2479
2480impl<'a> Replacer for &'a [u8] {
2481 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2482 caps.expand(*self, dst);
2483 }
2484
2485 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2486 no_expansion(self)
2487 }
2488}
2489
2490impl<'a> Replacer for &'a Vec<u8> {
2491 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2492 caps.expand(*self, dst);
2493 }
2494
2495 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2496 no_expansion(self)
2497 }
2498}
2499
2500impl Replacer for Vec<u8> {
2501 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2502 caps.expand(self, dst);
2503 }
2504
2505 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2506 no_expansion(self)
2507 }
2508}
2509
2510impl<'a> Replacer for Cow<'a, [u8]> {
2511 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2512 caps.expand(self.as_ref(), dst);
2513 }
2514
2515 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2516 no_expansion(self)
2517 }
2518}
2519
2520impl<'a> Replacer for &'a Cow<'a, [u8]> {
2521 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2522 caps.expand(self.as_ref(), dst);
2523 }
2524
2525 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2526 no_expansion(self)
2527 }
2528}
2529
2530impl<F, T> Replacer for F
2531where
2532 F: FnMut(&Captures<'_>) -> T,
2533 T: AsRef<[u8]>,
2534{
2535 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2536 dst.extend_from_slice((*self)(caps).as_ref());
2537 }
2538}
2539
2540/// A by-reference adaptor for a [`Replacer`].
2541///
2542/// This permits reusing the same `Replacer` value in multiple calls to a
2543/// replacement routine like [`Regex::replace_all`].
2544///
2545/// This type is created by [`Replacer::by_ref`].
2546#[derive(Debug)]
2547pub struct ReplacerRef<'a, R: ?Sized>(&'a mut R);
2548
2549impl<'a, R: Replacer + ?Sized + 'a> Replacer for ReplacerRef<'a, R> {
2550 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2551 self.0.replace_append(caps, dst)
2552 }
2553
2554 fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, [u8]>> {
2555 self.0.no_expansion()
2556 }
2557}
2558
2559/// A helper type for forcing literal string replacement.
2560///
2561/// It can be used with routines like [`Regex::replace`] and
2562/// [`Regex::replace_all`] to do a literal string replacement without expanding
2563/// `$name` to their corresponding capture groups. This can be both convenient
2564/// (to avoid escaping `$`, for example) and faster (since capture groups
2565/// don't need to be found).
2566///
2567/// `'s` is the lifetime of the literal string to use.
2568///
2569/// # Example
2570///
2571/// ```
2572/// use regex::bytes::{NoExpand, Regex};
2573///
2574/// let re = Regex::new(r"(?<last>[^,\s]+),\s+(\S+)").unwrap();
2575/// let result = re.replace(b"Springsteen, Bruce", NoExpand(b"$2 $last"));
2576/// assert_eq!(result, &b"$2 $last"[..]);
2577/// ```
2578#[derive(Clone, Debug)]
2579pub struct NoExpand<'s>(pub &'s [u8]);
2580
2581impl<'s> Replacer for NoExpand<'s> {
2582 fn replace_append(&mut self, _: &Captures<'_>, dst: &mut Vec<u8>) {
2583 dst.extend_from_slice(self.0);
2584 }
2585
2586 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2587 Some(Cow::Borrowed(self.0))
2588 }
2589}
2590
2591/// Quickly checks the given replacement string for whether interpolation
2592/// should be done on it. It returns `None` if a `$` was found anywhere in the
2593/// given string, which suggests interpolation needs to be done. But if there's
2594/// no `$` anywhere, then interpolation definitely does not need to be done. In
2595/// that case, the given string is returned as a borrowed `Cow`.
2596///
2597/// This is meant to be used to implement the `Replacer::no_expandsion` method
2598/// in its various trait impls.
2599fn no_expansion<T: AsRef<[u8]>>(replacement: &T) -> Option<Cow<'_, [u8]>> {
2600 let replacement: &[u8] = replacement.as_ref();
2601 match crate::find_byte::find_byte(needle:b'$', haystack:replacement) {
2602 Some(_) => None,
2603 None => Some(Cow::Borrowed(replacement)),
2604 }
2605}
2606