如何遍历字符串并替换某些短语? [英] How do I iterate through a string and replace certain phrases?

查看:42
本文介绍了如何遍历字符串并替换某些短语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将you are"替换为I am",将your"替换为my".我将如何在保持代码干燥的同时做到这一点?

I want to be able to replace phrases like "you are" to " I am" and "your" to "my". How would I do this while keeping my code DRY?

到目前为止我有这样的东西......

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 are" but not the "my" part.

我认为理想情况下它看起来像

I think ideally it'll look something 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)

推荐答案

让我们从 karthik manchala 回答和 Shepmaster 建议开始:

Let us start with karthik manchala answer and Shepmaster suggestion:

将所有字符串放在一个数组中并遍历该数组.如果你的应用逻辑是用B替换所有A,然后用D替换所有C,然后所有 E 和 F",那么代码将反映重复的逻辑.

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.

代码如下:

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;
            }
        }
    }
}

<小时>

就是这样,但为了完整起见,我想补充一点,如果您想要卓越的性能,那么您可以使用 PCREMARK 功能> 正则表达式引擎(pcre crate).


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).

使用 MARK 和这样的模式

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

您可以使用 MARK 编号进行分类,或者在您的情况下用作带有替换的数组的索引.这通常比使用多个正则表达式要好,因为主题字符串只处理一次.

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.

这篇关于如何遍历字符串并替换某些短语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆