如何在 Rust 中将输入设置为原始字符串?

How to set input as raw string in Rust?

如何让 Rust 将文本输入解释为原始文字字符串?我正在尝试制作一个 Regex 搜索功能,我在其中输入正则表达式并使用它来搜索一些文本:

...

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 会自动对输入进行转义,因此我无法将其用于 Regex。我知道您可以对字符串执行此操作:

r"Some text here with with escaping characters: \ "

但是我如何将它与变量一起使用呢?

Rust automatically escapes the input

不,不是。对于系统语言来说,这将是一个非常奇怪的决定。这是我构建的 MCVE

extern crate regex;

use std::io;
use regex::Regex;

static TEXT: &'static str = "Twas the best of times";

fn main() {
    let mut search_keyword = String::new();
    io::stdin().read_line(&mut search_keyword).unwrap();
    println!("You are searching: {:?}", search_keyword);

    let regex = Regex::new(search_keyword.trim()).unwrap();

    let matched = regex.is_match(TEXT);
    println!("Contains search term: {:?}", matched);
}

还有一个例子运行:

$ cargo run
     Running `target/debug/searcher`
Tw.s
You are searching: "Tw.s\n"
Contains search term: true

也许调试格式字符串 ({:?}) 的用法令人困惑?该格式使用 Debug 特性,它转义字符串中的非 ASCII 字符。