ansi_regex/
lib.rs

1extern crate regex;
2use regex::Regex;
3
4pub fn ansi_regex() -> Regex {
5    // TODO Can we support all the other sequences?
6    // See: chalk/ansi-regex
7    Regex::new(r"\x1b\[([\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e])").unwrap()
8}
9
10#[test]
11fn match_ansi_code_in_a_string() {
12    assert!(ansi_regex().is_match("\x1b[31mHello World\x1b[39m"));
13    assert!(ansi_regex().is_match("foo\u{001B}[4mcake\u{001B}[0m"));
14    assert!(ansi_regex().is_match("\u{001B}[4mcake\u{001B}[0m"));
15    assert!(ansi_regex().is_match("\u{001B}[0m\u{001B}[4m\u{001B}[42m\u{001B}[31mfoo\u{001B}[39m\u{001B}[49m\u{001B}[24mfoo\u{001B}[0m"));
16    assert!(ansi_regex().is_match("foo\u{001B}[mfoo"));
17}
18
19#[test]
20fn match_ansi_code_from_ls_command() {
21    assert!(ansi_regex().is_match("\u{001B}[00;38;5;244m\u{001B}[m\u{001B}[00;38;5;33mfoo\u{001B}[0m"));
22}
23
24#[test]
25fn match_reset_setfg_setbg_italics_strike_underline_sequence_in_a_string() {
26    let test_string = "\u{001B}[0;33;49;3;9;4mbar\u{001B}[0m";
27    let match_string= "\u{001B}[0;33;49;3;9;4m";
28
29    assert!(ansi_regex().is_match(&test_string));
30    assert!(ansi_regex().find(&test_string).unwrap().as_str() == match_string)
31}
32
33#[test]
34fn match_clear_tabs_sequence_in_a_string() {
35    let test_string="foo\u{001B}[0gbar";
36    let match_string= "\u{001B}[0g";
37
38    assert!(ansi_regex().is_match(&test_string));
39    assert!(ansi_regex().find(&test_string).unwrap().as_str() == match_string)
40}
41
42#[test]
43fn match_clear_line_from_cursor_right_in_a_string() {
44    let test_string="foo\u{001B}[Kbar";
45    let match_string= "\u{001B}[K";
46
47    assert!(ansi_regex().is_match(&test_string));
48    assert!(ansi_regex().find(&test_string).unwrap().as_str() == match_string)
49}
50
51#[test]
52fn match_clear_screen_in_a_string() {
53    let test_string="foo\u{001B}[2Jbar";
54    let match_string= "\u{001B}[2J";
55
56    assert!(ansi_regex().is_match(&test_string));
57    assert!(ansi_regex().find(&test_string).unwrap().as_str() == match_string)  
58}