使用C ++用正则表达式替换子字符串匹配

我使用std :: string regex_search和std :: string regex_replace查找子字符串并替换。我的问题是我不知道如何用正则表达式来表达它。当涉及到yy->%y时,其他情况如y,yyy,yyyy,yyyyy等。->%Y

std::string text = "y yyaa";
std::regex y_re("[yY]+"); // this is the regex that matches y yyy or more yyyy
std::regex yy_re("(?=^y{2}[^y])y{2}"); // this is the regex that matches only yy- my problem is here
std::string output = "";
smatch m;

if (regex_search(text,m,yy_re)) {
    output = std::regex_replace(text,yy_re,"%y");
}
else {
    output = std::regex_replace(text,y_re,"%Y");
}
cout << output << endl;

我的实际输出:

%Y %Yaa

我的预期输出:

%Y %yaa
z145071 回答:使用C ++用正则表达式替换子字符串匹配

您可以放心使用它,并使用更具体的正则表达式模式来匹配1)单个yY或3个或更多y / Y,或2)只有两个y / Y

std::string text = "y yyaa";
std::regex y_re("([^yY%]|^)[yY](?![yY])|[yY]{3,}"); // this is the regex that matches y yyy or more yyyy
std::regex yy_re("([^yY%]|^)[yY]{2}(?![yY])"); // this is the regex that matches only yy- my problem is here
std::string output = "";

output = std::regex_replace(text,yy_re,"$1%y");
output = std::regex_replace(output,y_re,"$1%Y");
std::cout << output << std::endl;

请参见online C++ demo

即使替换顺序未知,您也可以使用这种方法。

正则表达式详细信息

  • Regex 1 matches仅单个或3个或更多连续的y / Y
    • ([^yY%]|^)[yY](?![yY])-第1组:字符串开头或除yY%以外的任何字符,然后是Y或{{1} },然后不允许yy
    • Y-或
    • |-三个或更多[yY]{3,} / y s

正则表达式2的工作原理类似,仅Y matches只包含两个[yY]{2}y个字符。

替换内容包含对第1组值的反向引用,以放回捕获的字符。

本文链接:https://www.f2er.com/3167884.html

大家都在问