Convert non-regex string into regex

Using lazy-regex crate, I've this:

impl<'a> AnySvStrRegex for &'a str {
    fn convert(&self) -> Regex {
        let s = regex!(r"(?P<c>[\\~\^\$\&\-\.\*\+\?\(\)\[\]\{\}])")
            .replace_all(self, r"\$c").into_owned();
        Regex::new(s.as_ref()).unwrap()
    }
}

I've not tested it so far, but I think it's working. The purpose of this AnySvStrRegex trait is to allow some functions to take either a string or a regex. When such functions are given a string, the string must not be treated as regex.

So in the impl above I'm escaping every special character so that the string won't work as a regex. I'd like to know, is there a better way to do this?

One character I missed to escape is #. Does it have some meaning? Anyway, can I do this better?

You don't need to do this yourself. regex::escape will do it for you and it will always be correct and be guaranteed to provide a literal string that can be inserted into a regex without any meta characters.

You can see its implementation here: lib.rs - source

And yes, # is significant when the x mode is enabled. It lets you insert comments into your regex.

3 Likes