How to iterate over a string and replace certain phrases?

I want to replace phrases like "you" with "I" and "yours" with "mine." How do I do this while keeping my DRY code?

so far i have something like this ...

let re = Regex::new(r"you are").unwrap(); re.replace_all("you are awesome and so is your hat", "I am") 

But this only replaces the "you", but not the "my" part.

I think that ideally it would look like

 let re = Regex::new(r"your|you are").unwrap(); re.replace_all("you are awesome and so is your hat", fn_with_pattern_matching) 
0
source share
2 answers

Let's start with the answer of karthik manchala and Shepmaster :

put all the lines in an array and iterate over the array. If your application logic "replaces all A with B, then all C with D, then all E with F", then the code will reflect this repeating logic.

Instead of storing strings in an array, I would recommend storing compiled regular expressions there, so as not to rebuild them every time.

Here is the code:

 extern crate regex; use regex::Regex; use std::env::args; use std::iter::FromIterator; fn main() { let patterns = [("your", "mine"), ("you are", "I am")]; let patterns = Vec::from_iter(patterns.into_iter().map(|&(k, v)| { (Regex::new(k).expect(&format!("Can't compile the regular expression: {}", k)), v) })); for arg in args().skip(1) { println!("Argument: {}", arg); for &(ref re, replacement) in patterns.iter() { let got = re.replace_all(&arg, replacement); if got != arg { println!("Changed to: {}", got); continue; } } } } 

That would be so, but for completeness, I would like to add that if you want superior performance, you can use the MARK function, which is present in the PCRE regular expression engine ( pcre ).

With MARK and such patterns

 "(?x) ^ (?: (*MARK:0) first pattern \ | (*MARK:1) second pattern \ | (*MARK:2) third pattern \ )" 

you can use the MARK number for classification, or in your case as an index in an array with replacements. This is often better than using multiple regexes because the subject line is processed only once.

+1
source

You can do the following:

 let str = "you are awesome and so is your hat"; let re = Regex::new(r"you are").unwrap(); let re1 = Regex::new(r"your").unwrap(); re.replace_all(str, "I am"); re1.replace_all(str, "my"); 

Edit:

If you have many phrases to replace, create a map ("replace phrase", "replace phrase with") and repeat it to follow the above logic.

+1
source

Source: https://habr.com/ru/post/950972/


All Articles