2016-02-03 6 views
11

बनाने के लिए कैसे करें मेरे पास कई नियमित अभिव्यक्तियां हैं जिन्हें रन टाइम पर परिभाषित किया गया है और मैं उन्हें वैश्विक चर बनाना चाहता हूं।संकलित Regexp को वैश्विक चर

आप यह अनुमान लगा करने के लिए निम्न कोड काम करता है:

extern crate regex; 
use regex::Regex; 

fn main() { 
    let RE = Regex::new(r"hello (\w+)!").unwrap(); 
    let text = "hello bob!\nhello sue!\nhello world!\n"; 
    for cap in RE.captures_iter(text) { 
     println!("your name is: {}", cap.at(1).unwrap()); 
    } 
} 

लेकिन मैं यह कुछ इस तरह होना चाहते हैं:

extern crate regex; 
use regex::Regex; 

static 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.at(1).unwrap()); 
    } 
} 

हालांकि, मैं निम्नलिखित त्रुटि मिलती है:

Compiling global v0.1.0 (file:///home/garrett/projects/rag/global) 
src/main.rs:4:20: 4:56 error: method calls in statics are limited to constant inherent methods [E0378] 
src/main.rs:4 static RE: Regex = Regex::new(r"hello (\w+)!").unwrap(); 
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
src/main.rs:4:20: 4:56 help: run `rustc --explain E0378` to see a detailed explanation 
src/main.rs:4:20: 4:47 error: function calls in statics are limited to struct and enum constructors [E0015] 
src/main.rs:4 static RE: Regex = Regex::new(r"hello (\w+)!").unwrap(); 
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~ 
src/main.rs:4:20: 4:47 help: run `rustc --explain E0015` to see a detailed explanation 
src/main.rs:4:20: 4:47 note: a limited form of compile-time function evaluation is available on a nightly compiler via `const fn` 
src/main.rs:4 static RE: Regex = Regex::new(r"hello (\w+)!").unwrap(); 

क्या इसका मतलब यह है कि मुझे इन चरों को वैश्विक बनाने के लिए रात में जंग की जरूरत है, या वहां कोई दांत है ऐसा करने के लिए रास्ता?

उत्तर

11

आप इस तरह lazy_static मैक्रो का उपयोग कर सकते हैं:

extern crate regex; 

#[macro_use] 
extern crate lazy_static; 

use regex::Regex; 

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.at(1).unwrap()); 
    } 
} 
thankyou
+0

! यह आश्चर्यजनक रूप से अच्छी तरह से काम किया! – vitiral

+5

संयोग से, 'चलो पुनः' को छोड़ना संभव है: 'स्थिर रेफ आरई: रेगेक्स = रेगेक्स :: नया (...) अनचाप() 'काम करना चाहिए। – huon

+0

@huon अच्छा बिंदु। ऐसा इसलिए है क्योंकि रेगेक्स डीफ्रफ़ को सही करता है? – squiguy

संबंधित मुद्दे