Skip to content
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

captures #2

Open
ArtemGr opened this Issue Mar 21, 2015 · 2 comments

Comments

Projects
None yet
2 participants
@ArtemGr
Copy link

ArtemGr commented Mar 21, 2015

Here's an interesting improvement, IMHO:

pub struct ReIdx(regex::Regex, usize);
impl ReIdx {
  #[unstable]
  pub fn from_regex(re: regex::Regex) -> ReIdx {
    ReIdx(re, 0)
  }
  pub fn from_regex_group(re: regex::Regex, group: usize) -> ReIdx {
    ReIdx(re, group)
  }
}
#[stable(since="0.1.0")]
impl Index<ReIdx> for str {
  type Output = str;
  fn index<'a>(&'a self, index: &ReIdx) -> &'a str {
    match index.0.captures(self) {
      Some(captures) => match captures.pos (index.1) {
        Some ((start, end)) => &self[start .. end],
        None => &self[..0]
      },
      None => &self[..0]
    }
  }
}
impl Index<Result<ReIdx, regex::Error>> for str {
  type Output = str;
  fn index<'a>(&'a self, index: &Result<ReIdx, regex::Error>) -> &'a str {
    match *index {
      Ok(ref ri) => &self.index(ri),
      Err(_) => &self[..0]
    }
  }
}
#[macro_export]
macro_rules! ri {
  ($re:expr) => (ReIdx::from_regex($re));
  ($re:expr, $group:expr) => (ReIdx::from_regex_group($re,$group))
}

With it one can quickly switch from the whole match to a subgroup:

let foo = &uri[ri! (regex! (r"^/path/(\w+)/$"))];
let bar = &uri[ri! (regex! (r"^/path/(\w+)/$"), 1)];
@kstep

This comment has been minimized.

Copy link
Owner

kstep commented Mar 23, 2015

How about indexing by tuple?

let too = &uri[(ri![r"..."], 1)];
@kstep

This comment has been minimized.

Copy link
Owner

kstep commented Mar 23, 2015

I'm afraid to go too far in this experiment, as it will be very difficult to stop at some point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.