STD :: Regex_replace仅替换所有其他匹配

std::regex_replace only replaces every other match?

本文关键字:其他 Regex replace STD 替换      更新时间:2023-10-16

我需要解析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,,。但是,它不会查看其替换的内容,而只是替换之前的内容。它采取的步骤:

  1. 查找第一匹配:
  2. 替换第一匹配:,null,
  3. 继续前进,,只看到一个逗号,因为它仅在上一个搜索/替换之后查看字符串。

因此,您正在用,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,"));
相关文章: