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