escape_regex/
lib.rs

1/*!
2# Escape Regex
3
4Escape regular expression special characters in order to make it able to be concatenated safely by users.
5
6## Example
7
8```rust
9extern crate escape_regex;
10
11extern crate regex;
12
13use regex::Regex;
14
15let pattern = "123*456";
16let escaped_pattern = escape_regex::escape_string(pattern);
17
18let reg = Regex::new(&escaped_pattern).unwrap();
19
20assert_eq!(true, reg.is_match("0123*4567"));
21```
22*/
23
24static ESCAPE_CHARS: [char; 14] = ['$', '(', ')', '*', '+', '.', '?', '[', '\\', ']', '^', '{', '|', '}'];
25
26pub fn escape_string<S: AsRef<str>>(s: S) -> String {
27    let mut chars: Vec<char> = Vec::new();
28
29    for c in s.as_ref().chars() {
30        if let Ok(_) = ESCAPE_CHARS.binary_search(&c) {
31            chars.push('\\');
32        }
33        chars.push(c);
34    }
35
36    chars.into_iter().collect()
37}