How can I let Rust interpret a text input as a raw literal string? I am trying to make a Regex
search function where I take a regex input and use it to search through some text:
...
fn main() {
// Initiate file to search through
let text_path = Path::new("test.txt");
let mut text_file = File::open(text_path).unwrap();
let mut text = String::new();
text_file.read_to_string(&mut text);
// Search keyword
let mut search_keyword = String::new();
// Display filename and ask user for Regex
print!("Search (regex) in file[{path}]: ", path=text_path.display());
io::stdout().flush().ok();
// Get search keyword
io::stdin().read_line(&mut search_keyword).unwrap();
println!("You are searching: {:?}", search_keyword);
let search = to_regex(&search_keyword.trim()).is_match(&text);
println!("Contains search term: {:?}", search);
}
fn to_regex(keyword: &str) -> Regex {
Regex::new(keyword).unwrap()
}
Rust automatically escapes the input so I cannot use it for Regex
. I know you can do this for a string:
r"Some text here with with escaping characters: "
But how can I use that with a variable?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…