regex.rs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. use std::{str::FromStr, time::Instant};
  2. use regex::Regex;
  3. macro_rules! regex {
  4. ($re:literal $(,)?) => {{
  5. static RE: once_cell::sync::OnceCell<regex::Regex> = once_cell::sync::OnceCell::new();
  6. RE.get_or_init(|| regex::Regex::new($re).unwrap())
  7. }};
  8. }
  9. fn slow() {
  10. let s = r##"13.28.24.13 - - [10/Mar/2016:19:29:25 +0100] "GET /etc/lib/pChart2/examples/index.php?Action=View&Script=../../../../cnf/db.php HTTP/1.1" 404 151 "-" "HTTP_Request2/2.2.1 (http://pear.php.net/package/http_request2) PHP/5.3.16""##;
  11. let mut total = 0;
  12. for _ in 0..1000 {
  13. let re = Regex::new(
  14. r##"^(\S+) (\S+) (\S+) \[([^]]+)\] "([^"]*)" (\d+) (\d+) "([^"]*)" "([^"]*)"$"##,
  15. )
  16. .unwrap();
  17. let size = usize::from_str(re.captures(s).unwrap().get(7).unwrap().as_str()).unwrap();
  18. total += size;
  19. }
  20. println!("{}", total);
  21. }
  22. fn fast() {
  23. let s = r##"13.28.24.13 - - [10/Mar/2016:19:29:25 +0100] "GET /etc/lib/pChart2/examples/index.php?Action=View&Script=../../../../cnf/db.php HTTP/1.1" 404 151 "-" "HTTP_Request2/2.2.1 (http://pear.php.net/package/http_request2) PHP/5.3.16""##;
  24. let mut total = 0;
  25. for _ in 0..1000 {
  26. let re: &Regex = regex!(
  27. r##"^(\S+) (\S+) (\S+) \[([^]]+)\] "([^"]*)" (\d+) (\d+) "([^"]*)" "([^"]*)"$"##,
  28. );
  29. let size = usize::from_str(re.captures(s).unwrap().get(7).unwrap().as_str()).unwrap();
  30. total += size;
  31. }
  32. println!("{}", total);
  33. }
  34. fn main() {
  35. let t = Instant::now();
  36. slow();
  37. println!("slow: {:?}", t.elapsed());
  38. let t = Instant::now();
  39. fast();
  40. println!("fast: {:?}", t.elapsed());
  41. }