Search code examples
regexstringrustraw

How to insert a string slice into a raw string?


Whenever provided with a_new_phone_number of type &str I want to insert it somehow into a raw string for further input into Regex::new(). Is there a macro similar to format!() for that?

phone_number = Regex::new(r"(?xm)^.*{a_new_phone_number}.*$ ").unwrap();

Solution

  • You can use format!() for this.

    use regex::Regex;
    
    fn main() {
        let a_new_phone_number = "111-222-3333";
        let phone_number = Regex::new(&format!(r"(?m)^.? {}.?$ ", a_new_phone_number)).unwrap();
    }
    

    Bear in mind that if the regex itself has {} characters, see this Q&A for how to avoid problems. And if the user-provided string is not validated (or even if it is), it should probably be escaped as in this Q&A.