繁体   English   中英

多个正则表达式替换,会创建多个字符串吗?

[英]Multiple Regex Replace, does it create multiple strings?

所以我需要执行多个Regex Replaces,我想知道这是否是不好的做法,因为它可能会创建多个新字符串? 有一个更好的方法吗 ?

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]");

该方法的问题在于,您将浏览该字符串6次,如果将所有内容放在一个表达式中,则只会浏览该字符串一次。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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