diff options
| author | Eric Kidd <git@randomhacks.net> | 2014-12-13 13:33:18 -0500 |
|---|---|---|
| committer | Eric Kidd <git@randomhacks.net> | 2014-12-14 08:56:51 -0500 |
| commit | c2b0d7dd8818a0dca9b1fa7af6873375907f05ca (patch) | |
| tree | 369f80679f73646e73ed5f58b2041eb8183aa242 /src/libregex/lib.rs | |
| parent | 444fa1b7cffcd99ca5b8abb51acf979f06a25899 (diff) | |
| download | rust-c2b0d7dd8818a0dca9b1fa7af6873375907f05ca.tar.gz rust-c2b0d7dd8818a0dca9b1fa7af6873375907f05ca.zip | |
Modify `regex::Captures::{at,name}` to return `Option`
Closes #14602. As discussed in that issue, the existing `at` and `name`
functions represent two different results with the empty string:
1. Matched the empty string.
2. Did not match anything.
Consider the following example. This regex has two named matched
groups, `key` and `value`. `value` is optional:
```rust
// Matches "foo", "foo;v=bar" and "foo;v=".
regex!(r"(?P<key>[a-z]+)(;v=(?P<value>[a-z]*))?");
```
We can access `value` using `caps.name("value")`, but there's no way for
us to distinguish between the `"foo"` and `"foo;v="` cases.
Early this year, @BurntSushi recommended modifying the existing `at` and
`name` functions to return `Option`, instead of adding new functions to
the API.
This is a [breaking-change], but the fix is easy:
- `refs.at(1)` becomes `refs.at(1).unwrap_or("")`.
- `refs.name(name)` becomes `refs.name(name).unwrap_or("")`.
Diffstat (limited to 'src/libregex/lib.rs')
| -rw-r--r-- | src/libregex/lib.rs | 6 |
1 files changed, 4 insertions, 2 deletions
diff --git a/src/libregex/lib.rs b/src/libregex/lib.rs index 05f853a851e..3fadba9583e 100644 --- a/src/libregex/lib.rs +++ b/src/libregex/lib.rs @@ -103,7 +103,9 @@ //! let re = regex!(r"(\d{4})-(\d{2})-(\d{2})"); //! let text = "2012-03-14, 2013-01-01 and 2014-07-05"; //! for cap in re.captures_iter(text) { -//! println!("Month: {} Day: {} Year: {}", cap.at(2), cap.at(3), cap.at(1)); +//! println!("Month: {} Day: {} Year: {}", +//! cap.at(2).unwrap_or(""), cap.at(3).unwrap_or(""), +//! cap.at(1).unwrap_or("")); //! } //! // Output: //! // Month: 03 Day: 14 Year: 2012 @@ -285,7 +287,7 @@ //! # fn main() { //! let re = regex!(r"(?i)a+(?-i)b+"); //! let cap = re.captures("AaAaAbbBBBb").unwrap(); -//! assert_eq!(cap.at(0), "AaAaAbb"); +//! assert_eq!(cap.at(0), Some("AaAaAbb")); //! # } //! ``` //! |
