Skip to content

Add function to get position of named capture #276

Closed
@ghost

Description

It would be really, really convenient to get the position of a match returned by re.captures("something").name("capture_group_name").

I made a first attempt at implementing it based on what's available, but it's both buggy and inefficient...

extern crate regex;
use regex::{Regex, RegexSet, Captures};


fn get_named_capture_index(caps: &Captures, cap_name: &str) -> Option<usize> {
  let name_string = caps.name(cap_name);
  let mut res: Option<usize> = None;
  if let Some(name_string) = name_string {
    for (cap_ind, _) in caps.iter_pos().enumerate() {
      res = match caps.at(cap_ind) {
        Some(ind_string) => {
          if ind_string == name_string {
            Some(cap_ind)
          } else {
            None
          }
        },
        None => None
      };
    }
  }
  res
}

fn get_named_capture_position(caps: &Captures, cap_name: &str) ->
  Option<(usize, usize)> {
    let cap_ind = get_named_capture_index(caps, cap_name);
    if let Some(cap_ind) = cap_ind {
      caps.pos(cap_ind)
    } else {
      None
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions