0

每当提供 &str 类型的a_new_phone_number时,我想以某种方式将其插入原始字符串中,以便进一步输入 Regex::new()。是否有类似于 format!() 的宏?

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

1 回答 1

1

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.

于 2021-04-13T03:34:25.283 回答