Skip to content

Modify regex::Captures::{at,name} to return Option #19818

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 17, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/compiletest/compiletest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ fn extract_gdb_version(full_version_line: Option<String>) -> Option<String> {

match re.captures(full_version_line) {
Some(captures) => {
Some(captures.at(2).to_string())
Some(captures.at(2).unwrap_or("").to_string())
}
None => {
println!("Could not extract GDB version from line '{}'",
Expand Down Expand Up @@ -427,7 +427,7 @@ fn extract_lldb_version(full_version_line: Option<String>) -> Option<String> {

match re.captures(full_version_line) {
Some(captures) => {
Some(captures.at(1).to_string())
Some(captures.at(1).unwrap_or("").to_string())
}
None => {
println!("Could not extract LLDB version from line '{}'",
Expand Down
8 changes: 4 additions & 4 deletions src/compiletest/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ fn parse_expected(last_nonfollow_error: Option<uint>,
line: &str,
re: &Regex) -> Option<(WhichLine, ExpectedError)> {
re.captures(line).and_then(|caps| {
let adjusts = caps.name("adjusts").len();
let kind = caps.name("kind").to_ascii_lower();
let msg = caps.name("msg").trim().to_string();
let follow = caps.name("follow").len() > 0;
let adjusts = caps.name("adjusts").unwrap_or("").len();
let kind = caps.name("kind").unwrap_or("").to_ascii_lower();
let msg = caps.name("msg").unwrap_or("").trim().to_string();
let follow = caps.name("follow").unwrap_or("").len() > 0;

let (which, line) = if follow {
assert!(adjusts == 0, "use either //~| or //~^, not both.");
Expand Down
8 changes: 4 additions & 4 deletions src/grammar/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,10 +173,10 @@ fn parse_antlr_token(s: &str, tokens: &HashMap<String, token::Token>) -> TokenAn
);

let m = re.captures(s).expect(format!("The regex didn't match {}", s).as_slice());
let start = m.name("start");
let end = m.name("end");
let toknum = m.name("toknum");
let content = m.name("content");
let start = m.name("start").unwrap_or("");
let end = m.name("end").unwrap_or("");
let toknum = m.name("toknum").unwrap_or("");
let content = m.name("content").unwrap_or("");

let proto_tok = tokens.get(toknum).expect(format!("didn't find token {} in the map",
toknum).as_slice());
Expand Down
6 changes: 4 additions & 2 deletions src/libregex/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"));
//! # }
//! ```
//!
Expand Down
49 changes: 24 additions & 25 deletions src/libregex/re.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,9 +273,9 @@ impl Regex {
/// let re = regex!(r"'([^']+)'\s+\((\d{4})\)");
/// let text = "Not my favorite movie: 'Citizen Kane' (1941).";
/// let caps = re.captures(text).unwrap();
/// assert_eq!(caps.at(1), "Citizen Kane");
/// assert_eq!(caps.at(2), "1941");
/// assert_eq!(caps.at(0), "'Citizen Kane' (1941)");
/// assert_eq!(caps.at(1), Some("Citizen Kane"));
/// assert_eq!(caps.at(2), Some("1941"));
/// assert_eq!(caps.at(0), Some("'Citizen Kane' (1941)"));
/// # }
/// ```
///
Expand All @@ -291,9 +291,9 @@ impl Regex {
/// let re = regex!(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)");
/// let text = "Not my favorite movie: 'Citizen Kane' (1941).";
/// let caps = re.captures(text).unwrap();
/// assert_eq!(caps.name("title"), "Citizen Kane");
/// assert_eq!(caps.name("year"), "1941");
/// assert_eq!(caps.at(0), "'Citizen Kane' (1941)");
/// assert_eq!(caps.name("title"), Some("Citizen Kane"));
/// assert_eq!(caps.name("year"), Some("1941"));
/// assert_eq!(caps.at(0), Some("'Citizen Kane' (1941)"));
/// # }
/// ```
///
Expand Down Expand Up @@ -434,7 +434,7 @@ impl Regex {
/// # use regex::Captures; fn main() {
/// let re = regex!(r"([^,\s]+),\s+(\S+)");
/// let result = re.replace("Springsteen, Bruce", |&: caps: &Captures| {
/// format!("{} {}", caps.at(2), caps.at(1))
/// format!("{} {}", caps.at(2).unwrap_or(""), caps.at(1).unwrap_or(""))
/// });
/// assert_eq!(result.as_slice(), "Bruce Springsteen");
/// # }
Expand Down Expand Up @@ -712,27 +712,25 @@ impl<'t> Captures<'t> {
Some((self.locs[s].unwrap(), self.locs[e].unwrap()))
}

/// Returns the matched string for the capture group `i`.
/// If `i` isn't a valid capture group or didn't match anything, then the
/// empty string is returned.
pub fn at(&self, i: uint) -> &'t str {
/// Returns the matched string for the capture group `i`. If `i` isn't
/// a valid capture group or didn't match anything, then `None` is
/// returned.
pub fn at(&self, i: uint) -> Option<&'t str> {
match self.pos(i) {
None => "",
Some((s, e)) => {
self.text.slice(s, e)
}
None => None,
Some((s, e)) => Some(self.text.slice(s, e))
}
}

/// Returns the matched string for the capture group named `name`.
/// If `name` isn't a valid capture group or didn't match anything, then
/// the empty string is returned.
pub fn name(&self, name: &str) -> &'t str {
/// Returns the matched string for the capture group named `name`. If
/// `name` isn't a valid capture group or didn't match anything, then
/// `None` is returned.
pub fn name(&self, name: &str) -> Option<&'t str> {
match self.named {
None => "",
None => None,
Some(ref h) => {
match h.get(name) {
None => "",
None => None,
Some(i) => self.at(*i),
}
}
Expand Down Expand Up @@ -769,11 +767,12 @@ impl<'t> Captures<'t> {
// FIXME: Don't use regexes for this. It's completely unnecessary.
let re = Regex::new(r"(^|[^$]|\b)\$(\w+)").unwrap();
let text = re.replace_all(text, |&mut: refs: &Captures| -> String {
let (pre, name) = (refs.at(1), refs.at(2));
let pre = refs.at(1).unwrap_or("");
let name = refs.at(2).unwrap_or("");
format!("{}{}", pre,
match from_str::<uint>(name.as_slice()) {
None => self.name(name).to_string(),
Some(i) => self.at(i).to_string(),
None => self.name(name).unwrap_or("").to_string(),
Some(i) => self.at(i).unwrap_or("").to_string(),
})
});
let re = Regex::new(r"\$\$").unwrap();
Expand Down Expand Up @@ -802,7 +801,7 @@ impl<'t> Iterator<&'t str> for SubCaptures<'t> {
fn next(&mut self) -> Option<&'t str> {
if self.idx < self.caps.len() {
self.idx += 1;
Some(self.caps.at(self.idx - 1))
Some(self.caps.at(self.idx - 1).unwrap_or(""))
} else {
None
}
Expand Down