c++ - 如何仅替换 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>
谢谢
解决方案
您的代码的固定版本:
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...);
}
推荐阅读
- python - 如何在烧瓶中显示来自mysql数据库的任何文件,如pdf,文本,doc
- sql - 如果 cpu 已经未充分利用,我可以减少 Amazon postgreSQL RDS 交换内存使用量吗?
- windows - 如何使 Unix 终端文本颜色在 Windows 终端上显示相同(cmd/powershell)
- java - 无法从浮点数转换为双精度数?
- java - Spring Boot 合并配置属性
- elasticsearch - ElasticSearch:不匹配
- c++ - 将 vector::size() 分配给自动 const 引用是一种不好的做法吗?
- python - 使用 Jax 的偏导数?
- c - 如何在 C 中返回列表?
- apache - www.api.domain.com 指向一个页面,而 api.domain.com 指向另一个页面。www.domain.com 有效,但 domain.com 无效。是什么赋予了?