Let us start with karthik manchala
answer and Shepmaster
suggestion:
place all the strings in an array and iterate over the array. If your
application logic is "replace all A with B, then all C with D, then
all E with F", then the code will reflect that repeated logic.
Instead of keeping the strings in an array I would recommend storing the compiled regular expressions there in order not to rebuild them every time.
Here's 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 it, but for the sake of completeness I'd like to add that if you want superior performance then you might use the MARK
feature present in the PCRE
regular expressions engine (pcre crate).
With MARK
and a patterns like this
"(?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 into an array with replacements. This is often better than using multiple regular expressions because the subject string is only processed once.