-
Notifications
You must be signed in to change notification settings - Fork 0
/
fancy_regex_find_iter.rs
48 lines (42 loc) · 1.14 KB
/
fancy_regex_find_iter.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use fancy_regex::Regex;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Match<'t> {
text: &'t str,
start: usize,
end: usize,
}
impl<'t> Match<'t> {
pub fn start(&self) -> usize {
self.start
}
pub fn end(&self) -> usize {
self.end
}
}
pub fn regex_find_iter<'a>(regex: &Regex, text: &'a str) -> Vec<Match<'a>> {
let mut matches = Vec::<Match>::new();
let mut offset = 0;
while let Some(_match) = regex.find(&text[offset..]).unwrap() {
matches.push(Match {
text,
start: offset + _match.start(),
end: offset + _match.end(),
});
offset += _match.end();
}
matches
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_regex_find_iter() {
let text = "Retroactively relinquishing remunerations is reprehensible.";
let regex = Regex::new(r"\b\w{13}\b").unwrap();
let matches: Vec<(usize, usize)> = regex_find_iter(®ex, text)
.iter()
.map(|m| (m.start(), m.end()))
.collect();
assert_eq!(&matches, &[(0, 13), (14, 27), (28, 41), (45, 58)]);
}
}