简体   繁体   中英

Multiple Regex Replace, does it create multiple strings?

So I need to perform multiple Regex Replaces, I was wondering if this was bad practice since it might create multiple new strings ? Is there a better way to do this ?

var AllVariants = Regex.Replace(s, "5|S", "[5|S]");
AllVariants = Regex.Replace(AllVariants, "6|G", "[6|G]");
AllVariants = Regex.Replace(AllVariants, "8|B", "[8|B]");
AllVariants = Regex.Replace(AllVariants, "4|A", "[4|A]");
AllVariants = Regex.Replace(AllVariants, "1|I", "[1|I]");
AllVariants = Regex.Replace(AllVariants, "0|O", "[O|0]");

The problem with your approach is that you will browse the string 6 times, if you put all in one expression, you will browse the string only once.

string[] corr = {"[5|S]", "[6|G]", "[8|B]", "[4|A]", "[1|I]", "[0|O]"};

Regex reg = new Regex(@"([5S])|([6G])|([8B])|([4A])|([1I])|([0O])");

var AllVariants = reg.Replace(s, delegate(Match m) {
    for (int key = 0; key < corr.Length; ++key)
        if (string.IsNullOrEmpty(m.Groups[key+1].Value) == false) break;
    return corr[key];
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM