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

问题描述:

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

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

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?

Rust自动转义输入

Rust automatically escapes the input

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

No, it doesn't. That would be a very strange decision for a systems language. Here's the MCVE that I constructed:

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字符.

Perhaps the usage of the debugging format string ({:?}) is confusing? That formats using the Debug trait, which escapes non-ASCII characters in strings.