Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

regex - How to set input as raw string in Rust?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...