STD :: Regex_replace仅替换所有其他匹配
std::regex_replace only replaces every other match?
我需要解析json strings(带有boost :: property_tree :: read_json)
一些输入字符串无效,因为它们看起来像:
"[1,2,3,,,,,4]"
当它们需要看起来像:
时"[1,2,3,null,null,null,null,4]"
转换这种字符串的最佳方法是什么?
我尝试了
//option A:
std::regex rx1(",,");
auto out_str = std::regex_replace(str_in, rx1, std::string(",null,"));
和
//option B:
auto out_str = boost::algorithm::replace_all_copy(str_in, ",,", ",null,");
,但这两个选项都只能替换其他所有匹配项。如:
"[1,2,3,null,,null,,4]"
从根本上讲,我想要的不是要替换,而是要插入一个子字符串。id喜欢避免写回我要匹配的字符。
编辑:
我想要的不是消耗或插入逗号。像
//option C
std::regex rx1(",(),");
auto out_str = std::regex_replace(str_in, rx1, std::string("null"));
但这不起作用(可能是因为它是不正确的Regex语法)
您实际上不需要正则要执行这样的简单任务,简单的搜索和插入将有效:
#include <iostream>
using namespace std;
int main() {
std::string str{ "[1,2,3,,,,,4]" };
do {
auto pos = str.find( ",," );
if( pos == std::string::npos )
break;
str.insert( pos + 1, "null" );
} while( true );
std::cout << str << std::endl;
return 0;
}
在IDEONE上运行
regex
通过搜索第一个匹配,然后替换它。重叠的匹配项不会进行。因此,如果看到,,,
,它将用,null,
替换前两个逗号,从而产生,null,,
。但是,它不会查看其替换的内容,而只是替换之前的内容。它采取的步骤:
- 查找第一匹配:,,
- 替换第一匹配:,null,,
- 继续前进,,只看到一个逗号,因为它仅在上一个搜索/替换之后查看字符串。
因此,您正在用,null,
替换,,
,但它不查看您在替换字符串,null,
中使用的逗号,因为它不进行重叠匹配。
要确保它 do 进行重叠匹配,只需运行搜索并在字符串上两次替换。
您的替换字符串不正确。手工做:
Start: "[1,2,3,,,,,4]"
Replacement 1: "[1,2,3,null,|,,,4]"
^parsed up to here
Repalcement 2: "[1,2,3,null,,null,|,4]"
^parsed to here, no more matches
您要么想调整替换字符串,要么重复替换直到字符串不更改。
auto out_str = str_in;
while (out_str.find(",,") != std::string::npos) {
out_str = boost::algorithm::replace_all_copy(out_str, ",,", ",null,");
}
您可以两次调用功能(尽管不是最佳解决方案)
std::string in_str = "[1,2,3,,,,,4]";
std::regex rx1(",,");
auto out_str = std::regex_replace(in_str, rx1, std::string(",null,"));
out_str = std::regex_replace(out_str, rx1, std::string(",null,"));
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 在其他文件中创建类时在 c++ 项目中不起作用
- 类与私有变量的其他类之间的线程安全性
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- 此模式的C++RegEx
- GlobalAlloc而不是其他分配方法
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 断言中的Fold表达式在某些计算机上编译,但在其他计算机上不编译
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 结构和双指针隐藏在其他结构中,多层混淆
- UE4在OnComponentBeginOverlap上铸造其他actor
- 当我在其中一个线程执行中(在activemq-cpp中)捕获到特定值时,我如何终止/停止所有其他线程
- MESI协议和std::atomic-它是否确保所有写入立即对其他线程可见?
- 保留对其他类的成员函数的引用
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- <vector> 即使它已经包含在例如或其他人中,我是否应该包括<regex>?