From 0fd76b8e90470b99f3e5c968b65562fde56d0c3e Mon Sep 17 00:00:00 2001 From: Joursoir Date: Fri, 3 Mar 2023 00:00:55 +0400 Subject: add option to match only whole words --- src/lib.rs | 8 ++++++-- src/main.rs | 6 +++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index a716d13..eb43876 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,9 +5,13 @@ pub fn search<'a>(pattern: &str, contents: &'a str) -> Vec<&'a str> { .collect() } -pub fn contains_pattern(src: &str, pat: &str, ignore_case: bool) -> bool { +pub fn contains_pattern(src: &str, pat: &str, ignore_case: bool, word_regexp: bool) -> bool { let src = if ignore_case { src.to_lowercase() } else { src.to_owned() }; let pat = if ignore_case { pat.to_lowercase() } else { pat.to_owned() }; - src.contains(&pat) + if word_regexp { + src.split_whitespace().any(|p| p == pat) + } else { + src.contains(&pat) + } } diff --git a/src/main.rs b/src/main.rs index 3111766..33de082 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,6 +18,10 @@ struct Config { /// Ignores the case of the search string #[arg(short, long)] ignore_case: bool, + + /// Matches only whole words + #[arg(short, long)] + word_regexp: bool, } fn main() { @@ -48,7 +52,7 @@ fn run(config: Config) -> Result<(), Box> { }; for line in reader.lines().map(|l| l.unwrap()) { - if !trgrep::contains_pattern(&line, &config.pattern, config.ignore_case) { + if !trgrep::contains_pattern(&line, &config.pattern, config.ignore_case, config.word_regexp) { continue; } println!("{line}"); -- cgit v1.2.3-18-g5258