やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

Rustで正規表現(regex 3)

 正規表現を1度だけコンパイルするようにして効率化。

成果物

コード

Cargo.toml

[dependencies]
regex = "1"
lazy_static = "1"

main.rs

#[macro_use]
extern crate lazy_static;
use regex::Regex;

fn main() {
    const CONTENTS: &'static str = r#"AAA
        2019-07-29 BBB
        CCC 2019-07-30 DDD"#;
    let re = Regex::new(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})").unwrap();
    for caps in re.captures_iter(CONTENTS) {
        println!("year: {}, month: {}, day: {}",
            caps.get(1).unwrap().as_str(),
            caps.get(2).unwrap().as_str(),
            caps.get(3).unwrap().as_str());
    }
    println!("{}", some_helper_function(CONTENTS));
    println!("{}", some_helper_function("A2019-07B"));
    println!("{}", some_helper_function("A2019-07-29B"));
}
fn some_helper_function(text: &str) -> bool {
    lazy_static! {
        static ref RE: Regex = Regex::new(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})").unwrap();
    }
    RE.is_match(text)
}

実行

$ cargo run
...
year: 2019, month: 07, day: 29
year: 2019, month: 07, day: 30
true
false
true

所感

 lazy_staticという別のクレートと連携。よくわからんが、グローバル変数をつくるヤツなんだろう。

参考

対象環境

$ uname -a
Linux raspberrypi 4.19.42-v7+ #1219 SMP Tue May 14 21:20:58 BST 2019 armv7l GNU/Linux

前回まで