Struct Captures

Source
pub struct Captures<'t> { /* private fields */ }
Expand description

Captures represents a group of captured strings for a single match.

The 0th capture always corresponds to the entire match. Each subsequent index corresponds to the next capture group in the regex. Positions returned from a capture group are always byte indices.

't is the lifetime of the matched text.

Implementations§

Source§

impl<'t> Captures<'t>

Source

pub fn pos(&self, pos: usize) -> Option<(usize, usize)>

Returns the start and end positions of the Nth capture group. Returns None if i is not a valid capture group or if the capture group did not match anything. The positions returned are always byte indices with respect to the original string matched.

Source

pub fn at(&self, pos: usize) -> Option<&'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.

Examples found in repository?
examples/dollar.rs (line 13)
12fn capture_str<'t>(caps: &'t Captures, cap_ref: &str) -> Option<&'t str> {
13    cap_ref.parse::<usize>().ok().and_then(|p| caps.at(p))
14}
Source

pub fn len(&self) -> usize

Returns the number of captured groups.

Source

pub fn is_empty(&self) -> bool

Returns true if and only if there are no captured groups.

Source

pub fn iter(&'t self) -> SubCaptures<'t>

Creates an iterator of all the capture groups in order of appearance in the regular expression.

Examples found in repository?
examples/capturedump.rs (line 29)
7fn main() {
8    let mut regexes = HashMap::new();
9    for arg in env::args().skip(1) {
10        println!("Compiling '{}'", arg);
11        let regex_compilation = Regex::new(&arg);
12        match regex_compilation {
13            Ok(regex) => {
14                regexes.insert(arg, regex);
15            }
16            Err(error) => {
17                panic!("{:?}", error);
18            }
19        }
20    }
21
22    let stdin = io::stdin();
23    for line in stdin.lock().lines() {
24        if let Ok(line) = line {
25            for (name, regex) in regexes.iter() {
26                let res = regex.captures(&line);
27                match res {
28                    Some(captures) => {
29                        for (i, mat) in captures.iter().enumerate() {
30                            println!("{} => '{}'", i, mat.unwrap());
31                        }
32                    }
33                    None => println!("{} => did not match", name),
34                }
35            }
36        }
37    }
38}
Source

pub fn iter_pos(&'t self) -> SubCapturesPos<'t>

Creates an iterator of all the capture group positions in order of appearance in the regular expression. Positions are byte indices in terms of the original string matched.

Examples found in repository?
examples/scan.rs (line 7)
3fn scan_callback<'t>(n: i32, caps: Captures<'t>) -> bool {
4    println!("scan: {}", n);
5    println!("match at {}", caps.offset());
6
7    for (i, cap) in caps.iter_pos().enumerate() {
8        match cap {
9            Some(pos) => println!("{}: {:?}", i, pos),
10            None => println!("{}: did not capture", i),
11        }
12    }
13
14    true
15}
More examples
Hide additional examples
examples/simple.rs (line 12)
3fn main() {
4    let pattern = "a(.*)b|[e-f]+";
5    let string = "zzzzaffffffffb";
6
7    let r = Regex::new(pattern).unwrap();
8
9    match r.captures(string) {
10        Some(caps) => {
11            println!("match at {}", caps.offset());
12            for (i, cap) in caps.iter_pos().enumerate() {
13                match cap {
14                    Some(pos) => println!("{}: {:?}", i, pos),
15                    None => println!("{}: did not capture", i),
16                }
17            }
18        }
19        None => println!("search fail"),
20    }
21}
examples/syntax.rs (line 9)
3fn exec(syntax: &Syntax, pattern: &str, to_search: &str) {
4    let reg = Regex::with_options(pattern, RegexOptions::REGEX_OPTION_NONE, syntax).unwrap();
5
6    match reg.captures(to_search) {
7        Some(caps) => {
8            println!("match at {}", caps.offset());
9            for (i, cap) in caps.iter_pos().enumerate() {
10                match cap {
11                    Some(pos) => println!("{}: {:?}", i, pos),
12                    None => println!("{}: did not capture", i),
13                }
14            }
15        }
16        None => println!("search fail"),
17    }
18}
examples/user_property.rs (line 27)
4fn main() {
5    define_user_property(
6        "HandakuonHiragana",
7        &[
8            (0x3071, 0x3071), // PA
9            (0x3074, 0x3074), // PI
10            (0x3077, 0x3077), // PU
11            (0x307a, 0x307a), // PE
12            (0x307d, 0x307d), // PO
13        ],
14    );
15
16    // "PA PI PU PE PO a"
17    let hay = [
18        0xe3, 0x81, 0xb1, 0xe3, 0x81, 0xb4, 0xe3, 0x81, 0xb7, 0xe3, 0x81, 0xba, 0xe3, 0x81, 0xbd,
19        'a' as u8,
20    ];
21    let hay = str::from_utf8(&hay).unwrap();
22    let reg = Regex::new("\\A(\\p{HandakuonHiragana}{5})\\p{^HandakuonHiragana}\\z").unwrap();
23
24    match reg.captures(hay) {
25        Some(caps) => {
26            println!("match at {}", caps.offset());
27            for (i, cap) in caps.iter_pos().enumerate() {
28                match cap {
29                    Some(pos) => println!("{}: {:?}", i, pos),
30                    None => println!("{}: did not capture", i),
31                }
32            }
33        }
34        None => println!("search fail"),
35    }
36}
examples/sql.rs (line 32)
3fn main() {
4    let mut syntax = Syntax::default().clone();
5
6    syntax.set_operators(SyntaxOperator::SYNTAX_OPERATOR_VARIABLE_META_CHARACTERS);
7    syntax.set_behavior(SyntaxBehavior::empty());
8    syntax.set_options(RegexOptions::REGEX_OPTION_MULTILINE);
9
10    syntax.set_meta_char(MetaCharType::META_CHAR_ESCAPE, MetaChar::Character('\\'));
11    syntax.set_meta_char(MetaCharType::META_CHAR_ANYCHAR, MetaChar::Character('_'));
12    syntax.set_meta_char(MetaCharType::META_CHAR_ANYTIME, MetaChar::Ineffective);
13    syntax.set_meta_char(
14        MetaCharType::META_CHAR_ZERO_OR_ONE_TIME,
15        MetaChar::Ineffective,
16    );
17    syntax.set_meta_char(
18        MetaCharType::META_CHAR_ONE_OR_MORE_TIME,
19        MetaChar::Ineffective,
20    );
21    syntax.set_meta_char(
22        MetaCharType::META_CHAR_ANYCHAR_ANYTIME,
23        MetaChar::Character('%'),
24    );
25
26    let reg =
27        Regex::with_options("\\_%\\\\__zz", RegexOptions::REGEX_OPTION_NONE, &syntax).unwrap();
28
29    match reg.captures("a_abcabcabc\\ppzz") {
30        Some(caps) => {
31            println!("match at {}", caps.offset());
32            for (i, cap) in caps.iter_pos().enumerate() {
33                match cap {
34                    Some(pos) => println!("{}: {:?}", i, pos),
35                    None => println!("{}: did not capture", i),
36                }
37            }
38        }
39        None => println!("search fail"),
40    }
41}
Source

pub fn offset(&self) -> usize

Offset of the captures within the given string slice.

Examples found in repository?
examples/scan.rs (line 5)
3fn scan_callback<'t>(n: i32, caps: Captures<'t>) -> bool {
4    println!("scan: {}", n);
5    println!("match at {}", caps.offset());
6
7    for (i, cap) in caps.iter_pos().enumerate() {
8        match cap {
9            Some(pos) => println!("{}: {:?}", i, pos),
10            None => println!("{}: did not capture", i),
11        }
12    }
13
14    true
15}
More examples
Hide additional examples
examples/simple.rs (line 11)
3fn main() {
4    let pattern = "a(.*)b|[e-f]+";
5    let string = "zzzzaffffffffb";
6
7    let r = Regex::new(pattern).unwrap();
8
9    match r.captures(string) {
10        Some(caps) => {
11            println!("match at {}", caps.offset());
12            for (i, cap) in caps.iter_pos().enumerate() {
13                match cap {
14                    Some(pos) => println!("{}: {:?}", i, pos),
15                    None => println!("{}: did not capture", i),
16                }
17            }
18        }
19        None => println!("search fail"),
20    }
21}
examples/syntax.rs (line 8)
3fn exec(syntax: &Syntax, pattern: &str, to_search: &str) {
4    let reg = Regex::with_options(pattern, RegexOptions::REGEX_OPTION_NONE, syntax).unwrap();
5
6    match reg.captures(to_search) {
7        Some(caps) => {
8            println!("match at {}", caps.offset());
9            for (i, cap) in caps.iter_pos().enumerate() {
10                match cap {
11                    Some(pos) => println!("{}: {:?}", i, pos),
12                    None => println!("{}: did not capture", i),
13                }
14            }
15        }
16        None => println!("search fail"),
17    }
18}
examples/user_property.rs (line 26)
4fn main() {
5    define_user_property(
6        "HandakuonHiragana",
7        &[
8            (0x3071, 0x3071), // PA
9            (0x3074, 0x3074), // PI
10            (0x3077, 0x3077), // PU
11            (0x307a, 0x307a), // PE
12            (0x307d, 0x307d), // PO
13        ],
14    );
15
16    // "PA PI PU PE PO a"
17    let hay = [
18        0xe3, 0x81, 0xb1, 0xe3, 0x81, 0xb4, 0xe3, 0x81, 0xb7, 0xe3, 0x81, 0xba, 0xe3, 0x81, 0xbd,
19        'a' as u8,
20    ];
21    let hay = str::from_utf8(&hay).unwrap();
22    let reg = Regex::new("\\A(\\p{HandakuonHiragana}{5})\\p{^HandakuonHiragana}\\z").unwrap();
23
24    match reg.captures(hay) {
25        Some(caps) => {
26            println!("match at {}", caps.offset());
27            for (i, cap) in caps.iter_pos().enumerate() {
28                match cap {
29                    Some(pos) => println!("{}: {:?}", i, pos),
30                    None => println!("{}: did not capture", i),
31                }
32            }
33        }
34        None => println!("search fail"),
35    }
36}
examples/sql.rs (line 31)
3fn main() {
4    let mut syntax = Syntax::default().clone();
5
6    syntax.set_operators(SyntaxOperator::SYNTAX_OPERATOR_VARIABLE_META_CHARACTERS);
7    syntax.set_behavior(SyntaxBehavior::empty());
8    syntax.set_options(RegexOptions::REGEX_OPTION_MULTILINE);
9
10    syntax.set_meta_char(MetaCharType::META_CHAR_ESCAPE, MetaChar::Character('\\'));
11    syntax.set_meta_char(MetaCharType::META_CHAR_ANYCHAR, MetaChar::Character('_'));
12    syntax.set_meta_char(MetaCharType::META_CHAR_ANYTIME, MetaChar::Ineffective);
13    syntax.set_meta_char(
14        MetaCharType::META_CHAR_ZERO_OR_ONE_TIME,
15        MetaChar::Ineffective,
16    );
17    syntax.set_meta_char(
18        MetaCharType::META_CHAR_ONE_OR_MORE_TIME,
19        MetaChar::Ineffective,
20    );
21    syntax.set_meta_char(
22        MetaCharType::META_CHAR_ANYCHAR_ANYTIME,
23        MetaChar::Character('%'),
24    );
25
26    let reg =
27        Regex::with_options("\\_%\\\\__zz", RegexOptions::REGEX_OPTION_NONE, &syntax).unwrap();
28
29    match reg.captures("a_abcabcabc\\ppzz") {
30        Some(caps) => {
31            println!("match at {}", caps.offset());
32            for (i, cap) in caps.iter_pos().enumerate() {
33                match cap {
34                    Some(pos) => println!("{}: {:?}", i, pos),
35                    None => println!("{}: did not capture", i),
36                }
37            }
38        }
39        None => println!("search fail"),
40    }
41}

Trait Implementations§

Source§

impl<'t> Debug for Captures<'t>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'t> Freeze for Captures<'t>

§

impl<'t> RefUnwindSafe for Captures<'t>

§

impl<'t> !Send for Captures<'t>

§

impl<'t> !Sync for Captures<'t>

§

impl<'t> Unpin for Captures<'t>

§

impl<'t> UnwindSafe for Captures<'t>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.