From 9d32f207d6593c6a661bd6bcb88fb8de02fa7498 Mon Sep 17 00:00:00 2001 From: Shiwin <shpiwan@gmail.com> Date: Fri, 20 Oct 2017 23:00:17 +0400 Subject: [PATCH] Implement $regex_replace (#555) --- examples/methods.ion | 2 ++ examples/methods.out | 1 + .../shell_expand/words/methods/strings.rs | 17 +++++++++++++++++ 3 files changed, 20 insertions(+) diff --git a/examples/methods.ion b/examples/methods.ion index 00f9df4d..5c937fa6 100644 --- a/examples/methods.ion +++ b/examples/methods.ion @@ -40,3 +40,5 @@ echo $join(array, "\n") let a = [1 2 3 4 5] let a = "1 2 3 4 5" echo $join(@split(a, " "), $join(a, " ")) + +echo $regex_replace("one two onemy anemy town", "\ o|\ a" "\ e") \ No newline at end of file diff --git a/examples/methods.out b/examples/methods.out index dfb76765..823c03d7 100644 --- a/examples/methods.out +++ b/examples/methods.out @@ -66,3 +66,4 @@ one two three apple sauce 11 2 3 4 521 2 3 4 531 2 3 4 541 2 3 4 55 +one two enemy enemy town diff --git a/src/parser/shell_expand/words/methods/strings.rs b/src/parser/shell_expand/words/methods/strings.rs index 7f819677..4b7ba443 100644 --- a/src/parser/shell_expand/words/methods/strings.rs +++ b/src/parser/shell_expand/words/methods/strings.rs @@ -3,6 +3,7 @@ use super::super::Select; use super::super::super::{expand_string, Expander, is_expression, slice}; use parser::assignments::is_array; use shell::plugins::methods::{self, MethodArguments, StringMethodPlugins}; +use regex::Regex; use std::path::Path; use sys; use unicode_segmentation::UnicodeSegmentation; @@ -118,6 +119,22 @@ impl<'a> StringMethod<'a> { _ => eprintln!("ion: replacen: three arguments required") } } + "regex_replace" => { + let mut args = pattern.array(); + match (args.next(),args.next()) { + (Some(replace),Some(with)) => { + match Regex::new(&replace){ + Ok(re) => { + let inp = &get_var!(); + let res = re.replace_all(&inp,&with[..]); + output.push_str(&res); + } + Err(_) => eprintln!("ion: regex_replace: error in regular expression {}",&replace) + } + } + _ => eprintln!("ion: regex_replace: two arguments required") + } + } "join" => { let pattern = pattern.join(" "); if let Some(array) = expand.array(variable, Select::All) { -- GitLab