How to make a compiled Regexp a global variable?

后端 未结 1 2010
清酒与你
清酒与你 2020-12-11 14:39

I have several regular expressions that are defined at runtime and I would like to make them global variables.

To give you an idea, the following code works:

相关标签:
1条回答
  • 2020-12-11 15:05

    You can use the lazy_static macro like this:

    use lazy_static::lazy_static; // 1.3.0
    use regex::Regex; // 1.1.5
    
    lazy_static! {
        static ref RE: Regex = Regex::new(r"hello (\w+)!").unwrap();
    }
    
    fn main() {
        let text = "hello bob!\nhello sue!\nhello world!\n";
        for cap in RE.captures_iter(text) {
            println!("your name is: {}", &cap[1]);
        }
    }
    

    If you are using the 2015 edition of Rust, you can still use lazy_static via:

    #[macro_use]
    extern crate lazy_static;
    
    0 讨论(0)
提交回复
热议问题