首页 > 解决方案 > 如何仅替换 regex_search 的第一个匹配项?

问题描述

我正在做一个练习:

为 myPrintf 模板函数添加代码,用于检查格式字符串中参数类型和类型规范的匹配。仅限于 %d 作为 int 的转换,然后 %f 作为 float 的转换,%s 作为 const char * 的转换。

这是我的代码:

#include <iostream>
#include <string>
#include <type_traits>
#include <cstring>
#include <algorithm>
#include <regex>
using namespace std;

最后,我将只打印这个字符串,并将所有 %d%f%s 更改为变量的值

auto myPrintf(const char* x){
    cout<< x;
}

这是我的模板:

template<typename T ,typename... Args>
auto myPrintf(const char* x, T t, Args... args){
  std::regex e("[%].");
       std::cmatch cm;
      if (std::regex_search (x,cm,e)) 
    {           
    if (std::is_integral_v<T> ){       
     const char* d="%d";
     if (strcmp(cm,d)==0){
     std::regex_replace (x,e,t,std::regex_constants::format_first_only);
     }
    if(std::is_floating_point_v<T> ){ 
     const char* f="%f";
     if (strcmp(cm,f)==0){
     std::regex_replace (x,e,t,std::regex_constants::format_first_only);
     }        
    }
    if constexpr (std::is_same_v<const char*, T>) { 
             const char* s="%s";
     if (strcmp(cm,s)==0){
     std::regex_replace (x,e,t,std::regex_constants::format_first_only);
     }
    }

    } 
    return myPrintf(x,args...);


}

int main () {

    int i1 = 5, i2 = 7;
    float f1 = 5.4, f2 = 7.3;
    const char* s1 = "ABC";
    const char* s2 = "PQR";
    
    myPrintf("Print with no args");
    myPrintf("Print mix with err  -> str = %s, int = %d, flo = %f, str = %s, int = %d",
                                          s1, i1, f1, i1, i2);
    return 0;
}

请给我应该用来替换 const char * 字符串中的值的函数。

编辑:

我现在有这个错误:无法将 'const value_type {aka const std::sub_match}' 转换为 'const char*' for argument '1' to 'int strcmp(const char*, const char*)'</p>

谢谢

标签: c++templatesc++17

解决方案


您的代码的固定版本:

auto myPrintf(const std::string& x){
    std::cout<< x;
}

template<typename T ,typename... Args>
auto myPrintf(std::string x, T t, Args... args){
    std::regex e("[%].");
    std::smatch cm;
    if (std::regex_search (x,cm,e)) 
    {           
        if constexpr (std::is_integral_v<T> ){       
            const char* d="%d";
            if (strcmp(cm[0].str().c_str(),d)==0){
                x = std::regex_replace (x,e, std::to_string(t),std::regex_constants::format_first_only);
            }
        }
        if constexpr (std::is_floating_point_v<T> ){ 
            const char* f="%f";
            if (strcmp(cm[0].str().c_str(),f)==0){
                x = std::regex_replace (x,e,std::to_string(t),std::regex_constants::format_first_only);
            }        
        }
        if constexpr (std::is_same_v<const char*, T>) { 
            const char* s="%s";
            if (strcmp(cm[0].str().c_str(),s)==0){
                x = std::regex_replace (x,e,t,std::regex_constants::format_first_only);
            }
        }
    } 
    return myPrintf(x,args...);
}

演示


推荐阅读