daily pastebin goal
47%
SHARE
TWEET

Untitled

a guest Aug 21st, 2018 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. extern crate regex; // 1.0.2
  2.  
  3. use regex::{Match, Regex};
  4.  
  5. #[derive(Debug)]
  6. struct Candidate<'a> {
  7.     text: &'a str,
  8.     mat: Option<Match<'a>>,
  9.     score: usize,
  10. }
  11.  
  12. fn score<'a>(re: &Regex, text: &'a str) -> Candidate<'a> {
  13.     match re.find(text) {
  14.         Some(m) => Candidate {
  15.             text,
  16.             mat: Some(m),
  17.             score: text.len() - m.start() + m.end(),
  18.         },
  19.         None => Candidate {
  20.             text,
  21.             mat: None,
  22.             score: 0,
  23.         },
  24.     }
  25. }
  26.  
  27. struct Search<'a> {
  28.     terms: &'a str,
  29.     re: Regex,
  30.     candidates: Vec<Candidate<'a>>,
  31. }
  32.  
  33. impl<'a> Search<'a> {
  34.     fn new(terms: &'a str) -> Search {
  35.         let raw_re = format!("(?i){}", terms);
  36.         let re = Regex::new(&raw_re).unwrap();
  37.         Search {
  38.             terms,
  39.             re,
  40.             candidates: Vec::new(),
  41.         }
  42.     }
  43.  
  44.     fn search(&mut self, items: &[&'a str]) -> usize {
  45.         self.candidates.clear();
  46.         for item in items {
  47.             self.candidates.push(score(&self.re, item));
  48.         }
  49.         self.candidates.len()
  50.     }
  51. }
  52.  
  53. fn print_score(candidate: &Candidate) {
  54.     println!("{:2} {}", candidate.score, candidate.text);
  55. }
  56.  
  57. fn main() {
  58. let items_path = vec![
  59.     "/project/serializer/place.py",
  60.     "/project/serializer/core/place.py",
  61.     "/project/serializer/core/lace.py",
  62.     "/project/serializers/Place.py",
  63.     ];
  64.     let items_symbols = [
  65.     "serializer.PlaceSerializer",
  66.     "serializer.ThingSerializer",
  67.     ];
  68.    
  69.     let search_string = "serializer place";
  70.     let re = Regex::new("(?i)(serializer).*(place)").unwrap();
  71.     println!("{}", search_string);
  72.     println!();
  73.     print_score(&score(&re, "/project/serializer/place.py"));
  74.     print_score(&score(&re, "/project/serializer/core/place.py"));
  75.     print_score(&score(&re, "/project/serializer/core/lace.py"));
  76.     print_score(&score(&re, "/project/serializers/Place.py"));
  77.     println!();
  78.     print_score(&score(&re, "serializer.PlaceSerializer"));
  79.     print_score(&score(&re, "serializer.ThingSerializer"));
  80.     println!();
  81.     let search = Search::new(search_string);
  82. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top