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