用std :: regex_replace重构MFC字符串替换

问题描述

我正在查看15年前编写的以下MFC代码。显然,这很不好,std::regex应该更好地解决这个问题。我有两个问题:

  1. std::regex是否可以有效地处理多个替换项目?例如一次替换两个“约翰”->“玛丽”,“鲍勃”->“爱丽丝”吗?

  2. 用于strInput.Replace("-01-","-1-");类型的替换,这是我能做的最好的事情:

    regex re("(-0)([123456789])(-)"); 
    strinput = std::regex_replace(strinput,re,"-" + "$2" + "-"); 
    

原始代码

         CString strInput = "....."; // MFC string
         strInput.Replace("-Jan-","-1-"); 
         strInput.Replace("-Feb-","-2-"); 
         strInput.Replace("-Mar-","-3-"); 
         strInput.Replace("-Apr-","-4-"); 
         strInput.Replace("-May-","-5-"); 
         strInput.Replace("-Jun-","-6-"); 
         strInput.Replace("-Jul-","-7-"); 
         strInput.Replace("-Aug-","-8-"); 
         strInput.Replace("-Sep-","-9-"); 
         strInput.Replace("-Oct-","-10-"); 
         strInput.Replace("-Nov-","-11-"); 
         strInput.Replace("-Dec-","-12-");      

         strInput.Replace("-01-","-1-"); 
         strInput.Replace("-02-","-2-"); 
         strInput.Replace("-03-","-3-"); 
         strInput.Replace("-04-","-4-"); 
         strInput.Replace("-05-","-5-"); 
         strInput.Replace("-06-","-6-"); 
         strInput.Replace("-07-","-7-"); 
         strInput.Replace("-08-","-8-"); 
         strInput.Replace("-09-","-9-"); 

         strInput.Replace("-01,","-1,"); 
         strInput.Replace("-02,"-2,"); 
         strInput.Replace("-03,"-3,"); 
         strInput.Replace("-04,"-4,"); 
         strInput.Replace("-05,"-5,"); 
         strInput.Replace("-06,"-6,"); 
         strInput.Replace("-07,"-7,"); 
         strInput.Replace("-08,"-8,"); 
         strInput.Replace("-09,"-9,");

解决方法

std :: regex是否可以有效地处理多个替换?例如一次替换两个“约翰”->“玛丽”,“鲍勃”->“爱丽丝”吗?

我不这样认为。

用于strInput.Replace("-01-","-1-");类型的替换

对于最后2个块,您可以执行以下操作:

std::regex_replace(s,std::regex("-0([1-9])(-|,)"),"-$1$2");

Demo

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...