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("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(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(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 = f.debug_struct("Match");
1542 fmt.field("start", &self.start).field("end", &self.end);
1543 if let Ok(s) = core::str::from_utf8(self.as_bytes()) {
1544 fmt.field("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("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 can
1572/// 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. For
1574/// example, say you want to match the individual letters in a 5-letter word:
1575///
1576/// ```text
1577/// (?<first>\w)(\w)(?:\w)\w(?<last>\w)
1578/// ```
1579///
1580/// This regex has 4 capture groups:
1581///
1582/// * The group at index `0` corresponds to the overall match. It is always
1583/// present in every match and never has a name.
1584/// * The group at index `1` with name `first` corresponding to the first
1585/// letter.
1586/// * The group at index `2` with no name corresponding to the second letter.
1587/// * The group at index `3` with name `last` corresponding to the fifth and
1588/// last letter.
1589///
1590/// Notice that `(?:\w)` was not listed above as a capture group despite it
1591/// being enclosed in parentheses. That's because `(?:pattern)` is a special
1592/// syntax that permits grouping but *without* capturing. The reason for not
1593/// treating it as a capture is that tracking and reporting capture groups
1594/// requires additional state that may lead to slower searches. So using as few
1595/// capture groups as possible can help performance. (Although the difference
1596/// in performance of a couple of capture groups is likely immaterial.)
1597///
1598/// Values with this type are created by [`Regex::captures`] or
1599/// [`Regex::captures_iter`].
1600///
1601/// `'h` is the lifetime of the haystack that these captures were matched from.
1602///
1603/// # Example
1604///
1605/// ```
1606/// use regex::bytes::Regex;
1607///
1608/// let re = Regex::new(r"(?<first>\w)(\w)(?:\w)\w(?<last>\w)").unwrap();
1609/// let caps = re.captures(b"toady").unwrap();
1610/// assert_eq!(b"toady", &caps[0]);
1611/// assert_eq!(b"t", &caps["first"]);
1612/// assert_eq!(b"o", &caps[2]);
1613/// assert_eq!(b"y", &caps["last"]);
1614/// ```
1615pub struct Captures<'h> {
1616 haystack: &'h [u8],
1617 caps: captures::Captures,
1618 static_captures_len: Option<usize>,
1619}
1620
1621impl<'h> Captures<'h> {
1622 /// Returns the `Match` associated with the capture group at index `i`. If
1623 /// `i` does not correspond to a capture group, or if the capture group did
1624 /// not participate in the match, then `None` is returned.
1625 ///
1626 /// When `i == 0`, this is guaranteed to return a non-`None` value.
1627 ///
1628 /// # Examples
1629 ///
1630 /// Get the substring that matched with a default of an empty string if the
1631 /// group didn't participate in the match:
1632 ///
1633 /// ```
1634 /// use regex::bytes::Regex;
1635 ///
1636 /// let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap();
1637 /// let caps = re.captures(b"abc123").unwrap();
1638 ///
1639 /// let substr1 = caps.get(1).map_or(&b""[..], |m| m.as_bytes());
1640 /// let substr2 = caps.get(2).map_or(&b""[..], |m| m.as_bytes());
1641 /// assert_eq!(substr1, b"123");
1642 /// assert_eq!(substr2, b"");
1643 /// ```
1644 #[inline]
1645 pub fn get(&self, i: usize) -> Option<Match<'h>> {
1646 self.caps
1647 .get_group(i)
1648 .map(|sp| Match::new(self.haystack, sp.start, sp.end))
1649 }
1650
1651 /// Returns the `Match` associated with the capture group named `name`. If
1652 /// `name` isn't a valid capture group or it refers to a group that didn't
1653 /// match, then `None` is returned.
1654 ///
1655 /// Note that unlike `caps["name"]`, this returns a `Match` whose lifetime
1656 /// matches the lifetime of the haystack in this `Captures` value.
1657 /// Conversely, the substring returned by `caps["name"]` has a lifetime
1658 /// of the `Captures` value, which is likely shorter than the lifetime of
1659 /// the haystack. In some cases, it may be necessary to use this method to
1660 /// access the matching substring instead of the `caps["name"]` notation.
1661 ///
1662 /// # Examples
1663 ///
1664 /// Get the substring that matched with a default of an empty string if the
1665 /// group didn't participate in the match:
1666 ///
1667 /// ```
1668 /// use regex::bytes::Regex;
1669 ///
1670 /// let re = Regex::new(
1671 /// r"[a-z]+(?:(?<numbers>[0-9]+)|(?<letters>[A-Z]+))",
1672 /// ).unwrap();
1673 /// let caps = re.captures(b"abc123").unwrap();
1674 ///
1675 /// let numbers = caps.name("numbers").map_or(&b""[..], |m| m.as_bytes());
1676 /// let letters = caps.name("letters").map_or(&b""[..], |m| m.as_bytes());
1677 /// assert_eq!(numbers, b"123");
1678 /// assert_eq!(letters, b"");
1679 /// ```
1680 #[inline]
1681 pub fn name(&self, name: &str) -> Option<Match<'h>> {
1682 self.caps
1683 .get_group_by_name(name)
1684 .map(|sp| Match::new(self.haystack, sp.start, sp.end))
1685 }
1686
1687 /// This is a convenience routine for extracting the substrings
1688 /// corresponding to matching capture groups.
1689 ///
1690 /// This returns a tuple where the first element corresponds to the full
1691 /// substring of the haystack that matched the regex. The second element is
1692 /// an array of substrings, with each corresponding to the to the substring
1693 /// that matched for a particular capture group.
1694 ///
1695 /// # Panics
1696 ///
1697 /// This panics if the number of possible matching groups in this
1698 /// `Captures` value is not fixed to `N` in all circumstances.
1699 /// More precisely, this routine only works when `N` is equivalent to
1700 /// [`Regex::static_captures_len`].
1701 ///
1702 /// Stated more plainly, if the number of matching capture groups in a
1703 /// regex can vary from match to match, then this function always panics.
1704 ///
1705 /// For example, `(a)(b)|(c)` could produce two matching capture groups
1706 /// or one matching capture group for any given match. Therefore, one
1707 /// cannot use `extract` with such a pattern.
1708 ///
1709 /// But a pattern like `(a)(b)|(c)(d)` can be used with `extract` because
1710 /// the number of capture groups in every match is always equivalent,
1711 /// even if the capture _indices_ in each match are not.
1712 ///
1713 /// # Example
1714 ///
1715 /// ```
1716 /// use regex::bytes::Regex;
1717 ///
1718 /// let re = Regex::new(r"([0-9]{4})-([0-9]{2})-([0-9]{2})").unwrap();
1719 /// let hay = b"On 2010-03-14, I became a Tenneessee lamb.";
1720 /// let Some((full, [year, month, day])) =
1721 /// re.captures(hay).map(|caps| caps.extract()) else { return };
1722 /// assert_eq!(b"2010-03-14", full);
1723 /// assert_eq!(b"2010", year);
1724 /// assert_eq!(b"03", month);
1725 /// assert_eq!(b"14", day);
1726 /// ```
1727 ///
1728 /// # Example: iteration
1729 ///
1730 /// This example shows how to use this method when iterating over all
1731 /// `Captures` matches in a haystack.
1732 ///
1733 /// ```
1734 /// use regex::bytes::Regex;
1735 ///
1736 /// let re = Regex::new(r"([0-9]{4})-([0-9]{2})-([0-9]{2})").unwrap();
1737 /// let hay = b"1973-01-05, 1975-08-25 and 1980-10-18";
1738 ///
1739 /// let mut dates: Vec<(&[u8], &[u8], &[u8])> = vec![];
1740 /// for (_, [y, m, d]) in re.captures_iter(hay).map(|c| c.extract()) {
1741 /// dates.push((y, m, d));
1742 /// }
1743 /// assert_eq!(dates, vec![
1744 /// (&b"1973"[..], &b"01"[..], &b"05"[..]),
1745 /// (&b"1975"[..], &b"08"[..], &b"25"[..]),
1746 /// (&b"1980"[..], &b"10"[..], &b"18"[..]),
1747 /// ]);
1748 /// ```
1749 ///
1750 /// # Example: parsing different formats
1751 ///
1752 /// This API is particularly useful when you need to extract a particular
1753 /// value that might occur in a different format. Consider, for example,
1754 /// an identifier that might be in double quotes or single quotes:
1755 ///
1756 /// ```
1757 /// use regex::bytes::Regex;
1758 ///
1759 /// let re = Regex::new(r#"id:(?:"([^"]+)"|'([^']+)')"#).unwrap();
1760 /// let hay = br#"The first is id:"foo" and the second is id:'bar'."#;
1761 /// let mut ids = vec![];
1762 /// for (_, [id]) in re.captures_iter(hay).map(|c| c.extract()) {
1763 /// ids.push(id);
1764 /// }
1765 /// assert_eq!(ids, vec![b"foo", b"bar"]);
1766 /// ```
1767 pub fn extract<const N: usize>(&self) -> (&'h [u8], [&'h [u8]; N]) {
1768 let len = self
1769 .static_captures_len
1770 .expect("number of capture groups can vary in a match")
1771 .checked_sub(1)
1772 .expect("number of groups is always greater than zero");
1773 assert_eq!(N, len, "asked for {} groups, but must ask for {}", N, len);
1774 // The regex-automata variant of extract is a bit more permissive.
1775 // It doesn't require the number of matching capturing groups to be
1776 // static, and you can even request fewer groups than what's there. So
1777 // this is guaranteed to never panic because we've asserted above that
1778 // the user has requested precisely the number of groups that must be
1779 // present in any match for this regex.
1780 self.caps.extract_bytes(self.haystack)
1781 }
1782
1783 /// Expands all instances of `$ref` in `replacement` to the corresponding
1784 /// capture group, and writes them to the `dst` buffer given. A `ref` can
1785 /// be a capture group index or a name. If `ref` doesn't refer to a capture
1786 /// group that participated in the match, then it is replaced with the
1787 /// empty string.
1788 ///
1789 /// # Format
1790 ///
1791 /// The format of the replacement string supports two different kinds of
1792 /// capture references: unbraced and braced.
1793 ///
1794 /// For the unbraced format, the format supported is `$ref` where `name`
1795 /// can be any character in the class `[0-9A-Za-z_]`. `ref` is always
1796 /// the longest possible parse. So for example, `$1a` corresponds to the
1797 /// capture group named `1a` and not the capture group at index `1`. If
1798 /// `ref` matches `^[0-9]+$`, then it is treated as a capture group index
1799 /// itself and not a name.
1800 ///
1801 /// For the braced format, the format supported is `${ref}` where `ref` can
1802 /// be any sequence of bytes except for `}`. If no closing brace occurs,
1803 /// then it is not considered a capture reference. As with the unbraced
1804 /// format, if `ref` matches `^[0-9]+$`, then it is treated as a capture
1805 /// group index and not a name.
1806 ///
1807 /// The braced format is useful for exerting precise control over the name
1808 /// of the capture reference. For example, `${1}a` corresponds to the
1809 /// capture group reference `1` followed by the letter `a`, where as `$1a`
1810 /// (as mentioned above) corresponds to the capture group reference `1a`.
1811 /// The braced format is also useful for expressing capture group names
1812 /// that use characters not supported by the unbraced format. For example,
1813 /// `${foo[bar].baz}` refers to the capture group named `foo[bar].baz`.
1814 ///
1815 /// If a capture group reference is found and it does not refer to a valid
1816 /// capture group, then it will be replaced with the empty string.
1817 ///
1818 /// To write a literal `$`, use `$$`.
1819 ///
1820 /// # Example
1821 ///
1822 /// ```
1823 /// use regex::bytes::Regex;
1824 ///
1825 /// let re = Regex::new(
1826 /// r"(?<day>[0-9]{2})-(?<month>[0-9]{2})-(?<year>[0-9]{4})",
1827 /// ).unwrap();
1828 /// let hay = b"On 14-03-2010, I became a Tenneessee lamb.";
1829 /// let caps = re.captures(hay).unwrap();
1830 ///
1831 /// let mut dst = vec![];
1832 /// caps.expand(b"year=$year, month=$month, day=$day", &mut dst);
1833 /// assert_eq!(dst, b"year=2010, month=03, day=14");
1834 /// ```
1835 #[inline]
1836 pub fn expand(&self, replacement: &[u8], dst: &mut Vec<u8>) {
1837 self.caps.interpolate_bytes_into(self.haystack, replacement, dst);
1838 }
1839
1840 /// Returns an iterator over all capture groups. This includes both
1841 /// matching and non-matching groups.
1842 ///
1843 /// The iterator always yields at least one matching group: the first group
1844 /// (at index `0`) with no name. Subsequent groups are returned in the order
1845 /// of their opening parenthesis in the regex.
1846 ///
1847 /// The elements yielded have type `Option<Match<'h>>`, where a non-`None`
1848 /// value is present if the capture group matches.
1849 ///
1850 /// # Example
1851 ///
1852 /// ```
1853 /// use regex::bytes::Regex;
1854 ///
1855 /// let re = Regex::new(r"(\w)(\d)?(\w)").unwrap();
1856 /// let caps = re.captures(b"AZ").unwrap();
1857 ///
1858 /// let mut it = caps.iter();
1859 /// assert_eq!(it.next().unwrap().map(|m| m.as_bytes()), Some(&b"AZ"[..]));
1860 /// assert_eq!(it.next().unwrap().map(|m| m.as_bytes()), Some(&b"A"[..]));
1861 /// assert_eq!(it.next().unwrap().map(|m| m.as_bytes()), None);
1862 /// assert_eq!(it.next().unwrap().map(|m| m.as_bytes()), Some(&b"Z"[..]));
1863 /// assert_eq!(it.next(), None);
1864 /// ```
1865 #[inline]
1866 pub fn iter<'c>(&'c self) -> SubCaptureMatches<'c, 'h> {
1867 SubCaptureMatches { haystack: self.haystack, it: self.caps.iter() }
1868 }
1869
1870 /// Returns the total number of capture groups. This includes both
1871 /// matching and non-matching groups.
1872 ///
1873 /// The length returned is always equivalent to the number of elements
1874 /// yielded by [`Captures::iter`]. Consequently, the length is always
1875 /// greater than zero since every `Captures` value always includes the
1876 /// match for the entire regex.
1877 ///
1878 /// # Example
1879 ///
1880 /// ```
1881 /// use regex::bytes::Regex;
1882 ///
1883 /// let re = Regex::new(r"(\w)(\d)?(\w)").unwrap();
1884 /// let caps = re.captures(b"AZ").unwrap();
1885 /// assert_eq!(caps.len(), 4);
1886 /// ```
1887 #[inline]
1888 pub fn len(&self) -> usize {
1889 self.caps.group_len()
1890 }
1891}
1892
1893impl<'h> core::fmt::Debug for Captures<'h> {
1894 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1895 /// A little helper type to provide a nice map-like debug
1896 /// representation for our capturing group spans.
1897 ///
1898 /// regex-automata has something similar, but it includes the pattern
1899 /// ID in its debug output, which is confusing. It also doesn't include
1900 /// that strings that match because a regex-automata `Captures` doesn't
1901 /// borrow the haystack.
1902 struct CapturesDebugMap<'a> {
1903 caps: &'a Captures<'a>,
1904 }
1905
1906 impl<'a> core::fmt::Debug for CapturesDebugMap<'a> {
1907 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1908 let mut map = f.debug_map();
1909 let names =
1910 self.caps.caps.group_info().pattern_names(PatternID::ZERO);
1911 for (group_index, maybe_name) in names.enumerate() {
1912 let key = Key(group_index, maybe_name);
1913 match self.caps.get(group_index) {
1914 None => map.entry(&key, &None::<()>),
1915 Some(mat) => map.entry(&key, &Value(mat)),
1916 };
1917 }
1918 map.finish()
1919 }
1920 }
1921
1922 struct Key<'a>(usize, Option<&'a str>);
1923
1924 impl<'a> core::fmt::Debug for Key<'a> {
1925 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1926 write!(f, "{}", self.0)?;
1927 if let Some(name) = self.1 {
1928 write!(f, "/{:?}", name)?;
1929 }
1930 Ok(())
1931 }
1932 }
1933
1934 struct Value<'a>(Match<'a>);
1935
1936 impl<'a> core::fmt::Debug for Value<'a> {
1937 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1938 use regex_automata::util::escape::DebugHaystack;
1939
1940 write!(
1941 f,
1942 "{}..{}/{:?}",
1943 self.0.start(),
1944 self.0.end(),
1945 DebugHaystack(self.0.as_bytes())
1946 )
1947 }
1948 }
1949
1950 f.debug_tuple("Captures")
1951 .field(&CapturesDebugMap { caps: self })
1952 .finish()
1953 }
1954}
1955
1956/// Get a matching capture group's haystack substring by index.
1957///
1958/// The haystack substring returned can't outlive the `Captures` object if this
1959/// method is used, because of how `Index` is defined (normally `a[i]` is part
1960/// of `a` and can't outlive it). To work around this limitation, do that, use
1961/// [`Captures::get`] instead.
1962///
1963/// `'h` is the lifetime of the matched haystack, but the lifetime of the
1964/// `&str` returned by this implementation is the lifetime of the `Captures`
1965/// value itself.
1966///
1967/// # Panics
1968///
1969/// If there is no matching group at the given index.
1970impl<'h> core::ops::Index<usize> for Captures<'h> {
1971 type Output = [u8];
1972
1973 // The lifetime is written out to make it clear that the &str returned
1974 // does NOT have a lifetime equivalent to 'h.
1975 fn index<'a>(&'a self, i: usize) -> &'a [u8] {
1976 self.get(i)
1977 .map(|m| m.as_bytes())
1978 .unwrap_or_else(|| panic!("no group at index '{}'", i))
1979 }
1980}
1981
1982/// Get a matching capture group's haystack substring by name.
1983///
1984/// The haystack substring returned can't outlive the `Captures` object if this
1985/// method is used, because of how `Index` is defined (normally `a[i]` is part
1986/// of `a` and can't outlive it). To work around this limitation, do that, use
1987/// [`Captures::get`] instead.
1988///
1989/// `'h` is the lifetime of the matched haystack, but the lifetime of the
1990/// `&str` returned by this implementation is the lifetime of the `Captures`
1991/// value itself.
1992///
1993/// `'n` is the lifetime of the group name used to index the `Captures` value.
1994///
1995/// # Panics
1996///
1997/// If there is no matching group at the given name.
1998impl<'h, 'n> core::ops::Index<&'n str> for Captures<'h> {
1999 type Output = [u8];
2000
2001 fn index<'a>(&'a self, name: &'n str) -> &'a [u8] {
2002 self.name(name)
2003 .map(|m| m.as_bytes())
2004 .unwrap_or_else(|| panic!("no group named '{}'", name))
2005 }
2006}
2007
2008/// A low level representation of the byte offsets of each capture group.
2009///
2010/// You can think of this as a lower level [`Captures`], where this type does
2011/// not support named capturing groups directly and it does not borrow the
2012/// haystack that these offsets were matched on.
2013///
2014/// Primarily, this type is useful when using the lower level `Regex` APIs such
2015/// as [`Regex::captures_read`], which permits amortizing the allocation in
2016/// which capture match offsets are stored.
2017///
2018/// In order to build a value of this type, you'll need to call the
2019/// [`Regex::capture_locations`] method. The value returned can then be reused
2020/// in subsequent searches for that regex. Using it for other regexes may
2021/// result in a panic or otherwise incorrect results.
2022///
2023/// # Example
2024///
2025/// This example shows how to create and use `CaptureLocations` in a search.
2026///
2027/// ```
2028/// use regex::bytes::Regex;
2029///
2030/// let re = Regex::new(r"(?<first>\w+)\s+(?<last>\w+)").unwrap();
2031/// let mut locs = re.capture_locations();
2032/// let m = re.captures_read(&mut locs, b"Bruce Springsteen").unwrap();
2033/// assert_eq!(0..17, m.range());
2034/// assert_eq!(Some((0, 17)), locs.get(0));
2035/// assert_eq!(Some((0, 5)), locs.get(1));
2036/// assert_eq!(Some((6, 17)), locs.get(2));
2037///
2038/// // Asking for an invalid capture group always returns None.
2039/// assert_eq!(None, locs.get(3));
2040/// # // literals are too big for 32-bit usize: #1041
2041/// # #[cfg(target_pointer_width = "64")]
2042/// assert_eq!(None, locs.get(34973498648));
2043/// # #[cfg(target_pointer_width = "64")]
2044/// assert_eq!(None, locs.get(9944060567225171988));
2045/// ```
2046#[derive(Clone, Debug)]
2047pub struct CaptureLocations(captures::Captures);
2048
2049/// A type alias for `CaptureLocations` for backwards compatibility.
2050///
2051/// Previously, we exported `CaptureLocations` as `Locations` in an
2052/// undocumented API. To prevent breaking that code (e.g., in `regex-capi`),
2053/// we continue re-exporting the same undocumented API.
2054#[doc(hidden)]
2055pub type Locations = CaptureLocations;
2056
2057impl CaptureLocations {
2058 /// Returns the start and end byte offsets of the capture group at index
2059 /// `i`. This returns `None` if `i` is not a valid capture group or if the
2060 /// capture group did not match.
2061 ///
2062 /// # Example
2063 ///
2064 /// ```
2065 /// use regex::bytes::Regex;
2066 ///
2067 /// let re = Regex::new(r"(?<first>\w+)\s+(?<last>\w+)").unwrap();
2068 /// let mut locs = re.capture_locations();
2069 /// re.captures_read(&mut locs, b"Bruce Springsteen").unwrap();
2070 /// assert_eq!(Some((0, 17)), locs.get(0));
2071 /// assert_eq!(Some((0, 5)), locs.get(1));
2072 /// assert_eq!(Some((6, 17)), locs.get(2));
2073 /// ```
2074 #[inline]
2075 pub fn get(&self, i: usize) -> Option<(usize, usize)> {
2076 self.0.get_group(i).map(|sp| (sp.start, sp.end))
2077 }
2078
2079 /// Returns the total number of capture groups (even if they didn't match).
2080 /// That is, the length returned is unaffected by the result of a search.
2081 ///
2082 /// This is always at least `1` since every regex has at least `1`
2083 /// capturing group that corresponds to the entire match.
2084 ///
2085 /// # Example
2086 ///
2087 /// ```
2088 /// use regex::bytes::Regex;
2089 ///
2090 /// let re = Regex::new(r"(?<first>\w+)\s+(?<last>\w+)").unwrap();
2091 /// let mut locs = re.capture_locations();
2092 /// assert_eq!(3, locs.len());
2093 /// re.captures_read(&mut locs, b"Bruce Springsteen").unwrap();
2094 /// assert_eq!(3, locs.len());
2095 /// ```
2096 ///
2097 /// Notice that the length is always at least `1`, regardless of the regex:
2098 ///
2099 /// ```
2100 /// use regex::bytes::Regex;
2101 ///
2102 /// let re = Regex::new(r"").unwrap();
2103 /// let locs = re.capture_locations();
2104 /// assert_eq!(1, locs.len());
2105 ///
2106 /// // [a&&b] is a regex that never matches anything.
2107 /// let re = Regex::new(r"[a&&b]").unwrap();
2108 /// let locs = re.capture_locations();
2109 /// assert_eq!(1, locs.len());
2110 /// ```
2111 #[inline]
2112 pub fn len(&self) -> usize {
2113 // self.0.group_len() returns 0 if the underlying captures doesn't
2114 // represent a match, but the behavior guaranteed for this method is
2115 // that the length doesn't change based on a match or not.
2116 self.0.group_info().group_len(PatternID::ZERO)
2117 }
2118
2119 /// An alias for the `get` method for backwards compatibility.
2120 ///
2121 /// Previously, we exported `get` as `pos` in an undocumented API. To
2122 /// prevent breaking that code (e.g., in `regex-capi`), we continue
2123 /// re-exporting the same undocumented API.
2124 #[doc(hidden)]
2125 #[inline]
2126 pub fn pos(&self, i: usize) -> Option<(usize, usize)> {
2127 self.get(i)
2128 }
2129}
2130
2131/// An iterator over all non-overlapping matches in a haystack.
2132///
2133/// This iterator yields [`Match`] values. The iterator stops when no more
2134/// matches can be found.
2135///
2136/// `'r` is the lifetime of the compiled regular expression and `'h` is the
2137/// lifetime of the haystack.
2138///
2139/// This iterator is created by [`Regex::find_iter`].
2140///
2141/// # Time complexity
2142///
2143/// Note that since an iterator runs potentially many searches on the haystack
2144/// and since each search has worst case `O(m * n)` time complexity, the
2145/// overall worst case time complexity for iteration is `O(m * n^2)`.
2146#[derive(Debug)]
2147pub struct Matches<'r, 'h> {
2148 haystack: &'h [u8],
2149 it: meta::FindMatches<'r, 'h>,
2150}
2151
2152impl<'r, 'h> Iterator for Matches<'r, 'h> {
2153 type Item = Match<'h>;
2154
2155 #[inline]
2156 fn next(&mut self) -> Option<Match<'h>> {
2157 self.it
2158 .next()
2159 .map(|sp| Match::new(self.haystack, sp.start(), sp.end()))
2160 }
2161
2162 #[inline]
2163 fn count(self) -> usize {
2164 // This can actually be up to 2x faster than calling `next()` until
2165 // completion, because counting matches when using a DFA only requires
2166 // finding the end of each match. But returning a `Match` via `next()`
2167 // requires the start of each match which, with a DFA, requires a
2168 // reverse forward scan to find it.
2169 self.it.count()
2170 }
2171}
2172
2173impl<'r, 'h> core::iter::FusedIterator for Matches<'r, 'h> {}
2174
2175/// An iterator over all non-overlapping capture matches in a haystack.
2176///
2177/// This iterator yields [`Captures`] values. The iterator stops when no more
2178/// matches can be found.
2179///
2180/// `'r` is the lifetime of the compiled regular expression and `'h` is the
2181/// lifetime of the matched string.
2182///
2183/// This iterator is created by [`Regex::captures_iter`].
2184///
2185/// # Time complexity
2186///
2187/// Note that since an iterator runs potentially many searches on the haystack
2188/// and since each search has worst case `O(m * n)` time complexity, the
2189/// overall worst case time complexity for iteration is `O(m * n^2)`.
2190#[derive(Debug)]
2191pub struct CaptureMatches<'r, 'h> {
2192 haystack: &'h [u8],
2193 it: meta::CapturesMatches<'r, 'h>,
2194}
2195
2196impl<'r, 'h> Iterator for CaptureMatches<'r, 'h> {
2197 type Item = Captures<'h>;
2198
2199 #[inline]
2200 fn next(&mut self) -> Option<Captures<'h>> {
2201 let static_captures_len = self.it.regex().static_captures_len();
2202 self.it.next().map(|caps| Captures {
2203 haystack: self.haystack,
2204 caps,
2205 static_captures_len,
2206 })
2207 }
2208
2209 #[inline]
2210 fn count(self) -> usize {
2211 // This can actually be up to 2x faster than calling `next()` until
2212 // completion, because counting matches when using a DFA only requires
2213 // finding the end of each match. But returning a `Match` via `next()`
2214 // requires the start of each match which, with a DFA, requires a
2215 // reverse forward scan to find it.
2216 self.it.count()
2217 }
2218}
2219
2220impl<'r, 'h> core::iter::FusedIterator for CaptureMatches<'r, 'h> {}
2221
2222/// An iterator over all substrings delimited by a regex match.
2223///
2224/// `'r` is the lifetime of the compiled regular expression and `'h` is the
2225/// lifetime of the byte string being split.
2226///
2227/// This iterator is created by [`Regex::split`].
2228///
2229/// # Time complexity
2230///
2231/// Note that since an iterator runs potentially many searches on the haystack
2232/// and since each search has worst case `O(m * n)` time complexity, the
2233/// overall worst case time complexity for iteration is `O(m * n^2)`.
2234#[derive(Debug)]
2235pub struct Split<'r, 'h> {
2236 haystack: &'h [u8],
2237 it: meta::Split<'r, 'h>,
2238}
2239
2240impl<'r, 'h> Iterator for Split<'r, 'h> {
2241 type Item = &'h [u8];
2242
2243 #[inline]
2244 fn next(&mut self) -> Option<&'h [u8]> {
2245 self.it.next().map(|span| &self.haystack[span])
2246 }
2247}
2248
2249impl<'r, 'h> core::iter::FusedIterator for Split<'r, 'h> {}
2250
2251/// An iterator over at most `N` substrings delimited by a regex match.
2252///
2253/// The last substring yielded by this iterator will be whatever remains after
2254/// `N-1` splits.
2255///
2256/// `'r` is the lifetime of the compiled regular expression and `'h` is the
2257/// lifetime of the byte string being split.
2258///
2259/// This iterator is created by [`Regex::splitn`].
2260///
2261/// # Time complexity
2262///
2263/// Note that since an iterator runs potentially many searches on the haystack
2264/// and since each search has worst case `O(m * n)` time complexity, the
2265/// overall worst case time complexity for iteration is `O(m * n^2)`.
2266///
2267/// Although note that the worst case time here has an upper bound given
2268/// by the `limit` parameter to [`Regex::splitn`].
2269#[derive(Debug)]
2270pub struct SplitN<'r, 'h> {
2271 haystack: &'h [u8],
2272 it: meta::SplitN<'r, 'h>,
2273}
2274
2275impl<'r, 'h> Iterator for SplitN<'r, 'h> {
2276 type Item = &'h [u8];
2277
2278 #[inline]
2279 fn next(&mut self) -> Option<&'h [u8]> {
2280 self.it.next().map(|span| &self.haystack[span])
2281 }
2282
2283 #[inline]
2284 fn size_hint(&self) -> (usize, Option<usize>) {
2285 self.it.size_hint()
2286 }
2287}
2288
2289impl<'r, 'h> core::iter::FusedIterator for SplitN<'r, 'h> {}
2290
2291/// An iterator over the names of all capture groups in a regex.
2292///
2293/// This iterator yields values of type `Option<&str>` in order of the opening
2294/// capture group parenthesis in the regex pattern. `None` is yielded for
2295/// groups with no name. The first element always corresponds to the implicit
2296/// and unnamed group for the overall match.
2297///
2298/// `'r` is the lifetime of the compiled regular expression.
2299///
2300/// This iterator is created by [`Regex::capture_names`].
2301#[derive(Clone, Debug)]
2302pub struct CaptureNames<'r>(captures::GroupInfoPatternNames<'r>);
2303
2304impl<'r> Iterator for CaptureNames<'r> {
2305 type Item = Option<&'r str>;
2306
2307 #[inline]
2308 fn next(&mut self) -> Option<Option<&'r str>> {
2309 self.0.next()
2310 }
2311
2312 #[inline]
2313 fn size_hint(&self) -> (usize, Option<usize>) {
2314 self.0.size_hint()
2315 }
2316
2317 #[inline]
2318 fn count(self) -> usize {
2319 self.0.count()
2320 }
2321}
2322
2323impl<'r> ExactSizeIterator for CaptureNames<'r> {}
2324
2325impl<'r> core::iter::FusedIterator for CaptureNames<'r> {}
2326
2327/// An iterator over all group matches in a [`Captures`] value.
2328///
2329/// This iterator yields values of type `Option<Match<'h>>`, where `'h` is the
2330/// lifetime of the haystack that the matches are for. The order of elements
2331/// yielded corresponds to the order of the opening parenthesis for the group
2332/// in the regex pattern. `None` is yielded for groups that did not participate
2333/// in the match.
2334///
2335/// The first element always corresponds to the implicit group for the overall
2336/// match. Since this iterator is created by a [`Captures`] value, and a
2337/// `Captures` value is only created when a match occurs, it follows that the
2338/// first element yielded by this iterator is guaranteed to be non-`None`.
2339///
2340/// The lifetime `'c` corresponds to the lifetime of the `Captures` value that
2341/// created this iterator, and the lifetime `'h` corresponds to the originally
2342/// matched haystack.
2343#[derive(Clone, Debug)]
2344pub struct SubCaptureMatches<'c, 'h> {
2345 haystack: &'h [u8],
2346 it: captures::CapturesPatternIter<'c>,
2347}
2348
2349impl<'c, 'h> Iterator for SubCaptureMatches<'c, 'h> {
2350 type Item = Option<Match<'h>>;
2351
2352 #[inline]
2353 fn next(&mut self) -> Option<Option<Match<'h>>> {
2354 self.it.next().map(|group| {
2355 group.map(|sp| Match::new(self.haystack, sp.start, sp.end))
2356 })
2357 }
2358
2359 #[inline]
2360 fn size_hint(&self) -> (usize, Option<usize>) {
2361 self.it.size_hint()
2362 }
2363
2364 #[inline]
2365 fn count(self) -> usize {
2366 self.it.count()
2367 }
2368}
2369
2370impl<'c, 'h> ExactSizeIterator for SubCaptureMatches<'c, 'h> {}
2371
2372impl<'c, 'h> core::iter::FusedIterator for SubCaptureMatches<'c, 'h> {}
2373
2374/// A trait for types that can be used to replace matches in a haystack.
2375///
2376/// In general, users of this crate shouldn't need to implement this trait,
2377/// since implementations are already provided for `&[u8]` along with other
2378/// variants of byte string types, as well as `FnMut(&Captures) -> Vec<u8>` (or
2379/// any `FnMut(&Captures) -> T` where `T: AsRef<[u8]>`). Those cover most use
2380/// cases, but callers can implement this trait directly if necessary.
2381///
2382/// # Example
2383///
2384/// This example shows a basic implementation of the `Replacer` trait. This can
2385/// be done much more simply using the replacement byte string interpolation
2386/// support (e.g., `$first $last`), but this approach avoids needing to parse
2387/// the replacement byte string at all.
2388///
2389/// ```
2390/// use regex::bytes::{Captures, Regex, Replacer};
2391///
2392/// struct NameSwapper;
2393///
2394/// impl Replacer for NameSwapper {
2395/// fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2396/// dst.extend_from_slice(&caps["first"]);
2397/// dst.extend_from_slice(b" ");
2398/// dst.extend_from_slice(&caps["last"]);
2399/// }
2400/// }
2401///
2402/// let re = Regex::new(r"(?<last>[^,\s]+),\s+(?<first>\S+)").unwrap();
2403/// let result = re.replace(b"Springsteen, Bruce", NameSwapper);
2404/// assert_eq!(result, &b"Bruce Springsteen"[..]);
2405/// ```
2406pub trait Replacer {
2407 /// Appends possibly empty data to `dst` to replace the current match.
2408 ///
2409 /// The current match is represented by `caps`, which is guaranteed to have
2410 /// a match at capture group `0`.
2411 ///
2412 /// For example, a no-op replacement would be
2413 /// `dst.extend_from_slice(&caps[0])`.
2414 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>);
2415
2416 /// Return a fixed unchanging replacement byte string.
2417 ///
2418 /// When doing replacements, if access to [`Captures`] is not needed (e.g.,
2419 /// the replacement byte string does not need `$` expansion), then it can
2420 /// be beneficial to avoid finding sub-captures.
2421 ///
2422 /// In general, this is called once for every call to a replacement routine
2423 /// such as [`Regex::replace_all`].
2424 fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, [u8]>> {
2425 None
2426 }
2427
2428 /// Returns a type that implements `Replacer`, but that borrows and wraps
2429 /// this `Replacer`.
2430 ///
2431 /// This is useful when you want to take a generic `Replacer` (which might
2432 /// not be cloneable) and use it without consuming it, so it can be used
2433 /// more than once.
2434 ///
2435 /// # Example
2436 ///
2437 /// ```
2438 /// use regex::bytes::{Regex, Replacer};
2439 ///
2440 /// fn replace_all_twice<R: Replacer>(
2441 /// re: Regex,
2442 /// src: &[u8],
2443 /// mut rep: R,
2444 /// ) -> Vec<u8> {
2445 /// let dst = re.replace_all(src, rep.by_ref());
2446 /// let dst = re.replace_all(&dst, rep.by_ref());
2447 /// dst.into_owned()
2448 /// }
2449 /// ```
2450 fn by_ref<'r>(&'r mut self) -> ReplacerRef<'r, Self> {
2451 ReplacerRef(self)
2452 }
2453}
2454
2455impl<'a, const N: usize> Replacer for &'a [u8; N] {
2456 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2457 caps.expand(&**self, dst);
2458 }
2459
2460 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2461 no_expansion(self)
2462 }
2463}
2464
2465impl<const N: usize> Replacer for [u8; N] {
2466 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2467 caps.expand(&*self, dst);
2468 }
2469
2470 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2471 no_expansion(self)
2472 }
2473}
2474
2475impl<'a> Replacer for &'a [u8] {
2476 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2477 caps.expand(*self, dst);
2478 }
2479
2480 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2481 no_expansion(self)
2482 }
2483}
2484
2485impl<'a> Replacer for &'a Vec<u8> {
2486 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2487 caps.expand(*self, dst);
2488 }
2489
2490 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2491 no_expansion(self)
2492 }
2493}
2494
2495impl Replacer for Vec<u8> {
2496 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2497 caps.expand(self, dst);
2498 }
2499
2500 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2501 no_expansion(self)
2502 }
2503}
2504
2505impl<'a> Replacer for Cow<'a, [u8]> {
2506 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2507 caps.expand(self.as_ref(), dst);
2508 }
2509
2510 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2511 no_expansion(self)
2512 }
2513}
2514
2515impl<'a> Replacer for &'a Cow<'a, [u8]> {
2516 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2517 caps.expand(self.as_ref(), dst);
2518 }
2519
2520 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2521 no_expansion(self)
2522 }
2523}
2524
2525impl<F, T> Replacer for F
2526where
2527 F: FnMut(&Captures<'_>) -> T,
2528 T: AsRef<[u8]>,
2529{
2530 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2531 dst.extend_from_slice((*self)(caps).as_ref());
2532 }
2533}
2534
2535/// A by-reference adaptor for a [`Replacer`].
2536///
2537/// This permits reusing the same `Replacer` value in multiple calls to a
2538/// replacement routine like [`Regex::replace_all`].
2539///
2540/// This type is created by [`Replacer::by_ref`].
2541#[derive(Debug)]
2542pub struct ReplacerRef<'a, R: ?Sized>(&'a mut R);
2543
2544impl<'a, R: Replacer + ?Sized + 'a> Replacer for ReplacerRef<'a, R> {
2545 fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut Vec<u8>) {
2546 self.0.replace_append(caps, dst)
2547 }
2548
2549 fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, [u8]>> {
2550 self.0.no_expansion()
2551 }
2552}
2553
2554/// A helper type for forcing literal string replacement.
2555///
2556/// It can be used with routines like [`Regex::replace`] and
2557/// [`Regex::replace_all`] to do a literal string replacement without expanding
2558/// `$name` to their corresponding capture groups. This can be both convenient
2559/// (to avoid escaping `$`, for example) and faster (since capture groups
2560/// don't need to be found).
2561///
2562/// `'s` is the lifetime of the literal string to use.
2563///
2564/// # Example
2565///
2566/// ```
2567/// use regex::bytes::{NoExpand, Regex};
2568///
2569/// let re = Regex::new(r"(?<last>[^,\s]+),\s+(\S+)").unwrap();
2570/// let result = re.replace(b"Springsteen, Bruce", NoExpand(b"$2 $last"));
2571/// assert_eq!(result, &b"$2 $last"[..]);
2572/// ```
2573#[derive(Clone, Debug)]
2574pub struct NoExpand<'s>(pub &'s [u8]);
2575
2576impl<'s> Replacer for NoExpand<'s> {
2577 fn replace_append(&mut self, _: &Captures<'_>, dst: &mut Vec<u8>) {
2578 dst.extend_from_slice(self.0);
2579 }
2580
2581 fn no_expansion(&mut self) -> Option<Cow<'_, [u8]>> {
2582 Some(Cow::Borrowed(self.0))
2583 }
2584}
2585
2586/// Quickly checks the given replacement string for whether interpolation
2587/// should be done on it. It returns `None` if a `$` was found anywhere in the
2588/// given string, which suggests interpolation needs to be done. But if there's
2589/// no `$` anywhere, then interpolation definitely does not need to be done. In
2590/// that case, the given string is returned as a borrowed `Cow`.
2591///
2592/// This is meant to be used to implement the `Replacer::no_expandsion` method
2593/// in its various trait impls.
2594fn no_expansion<T: AsRef<[u8]>>(replacement: &T) -> Option<Cow<'_, [u8]>> {
2595 let replacement = replacement.as_ref();
2596 match crate::find_byte::find_byte(b'$', replacement) {
2597 Some(_) => None,
2598 None => Some(Cow::Borrowed(replacement)),
2599 }
2600}
2601