2016-06-17 12 views
-1

Rustにテキスト入力を生のリテラル文字列として解釈させるにはどうすればよいですか?私は正規表現の入力を取るRegex検索機能を作成し、いくつかのテキストを検索するためにそれを使用しようとしています:私はRegexのためにそれを使用することはできませんので、入力をRustの生の文字列として設定する方法は?

... 

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

錆が自動的に入力をエスケープします。私はあなたが文字列のためにこれを行うことができることを知っています:

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

しかし、私はどのように変数でそれを使うことができますか?

+0

おそらく 'r#" somestring "#"をやってみてください... –

答えて

3

錆が自動的いいえ、そうでない入力

をエスケープします。それはシステム言語にとって非常に奇妙な決定になります。ここで私が構築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 

おそらくデバッグ用フォーマット文字列({:?})の使用量は混乱しているのですか?これは、文字列内の非ASCII文字をエスケープするDebug形質を使用してフォーマットされます。

関連する問題