Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
240 views
Welcome To Ask or Share your Answers For Others

1 Answer

Rust automatically escapes the input

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);
}

And an example of it running:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...