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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#[macro_use]
extern crate lazy_static;
extern crate regex;
#[cfg(test)]
extern crate itertools;
use regex::bytes::{Matches, Regex};
pub const ANSI_RE: &str =
r"[\x1b\x9b]\[[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]";
lazy_static! {
pub static ref ANSI_REGEX: Regex = Regex::new(ANSI_RE).unwrap();
}
pub fn parse_bytes(text: &[u8]) -> Matches {
ANSI_REGEX.find_iter(text)
}
#[cfg(test)]
mod tests {
use super::parse_bytes;
use itertools::zip_eq;
fn test_parse(text: &[u8], expected: &[(usize, usize, &[u8])]) {
for (match_, expected_match) in zip_eq(parse_bytes(text), expected.iter()) {
assert_eq!(
&(match_.start(), match_.end(), match_.as_bytes()),
expected_match,
);
}
}
#[test]
fn red_underline() {
test_parse(
b"before \x1b[31;4mred underline\x1b[0m after",
&[(7, 14, b"\x1b[31;4m"), (27, 31, b"\x1b[0m")],
);
}
}