我有一个RE2正则表达式,如下所示
const re2::RE2 numRegex("(([0-9]+),)+([0-9])+");
std::string inputStr;
inputStr="apple with make,up things $312,412,3.00");
RE2::Replace(&inputStr, numRegex, "$1$3");
cout << inputStr;期望的
apple with make,up,things $3124123.00我试图删除识别数字中的,,$1只匹配312,而不匹配412部件。想知道如何提取组中的递归模式。
请注意,RE2不支持前瞻性(请参阅使用正向前瞻(?=regex)和re2),我找到的解决方案都使用查找头。
发布于 2021-04-07 19:36:38
基于RE2的解决方案
由于RE2不支持旁观者,因此没有纯单通正则表达式解决方案。
您可以有一个解决方案(通常,当没有可用的解决方案时):用(\d),(\d) regex和$1$2替换两次替换字符串:
const re2::RE2 numRegex(R"((\d),(\d))");
std::string inputStr("apple with make,up things $312,412,3.00");
RE2::Replace(&inputStr, numRegex, "$1$2");
RE2::Replace(&inputStr, numRegex, "$1$2"); // <- Second pass to remove commas in 1,2,3,4 like strings
std::cout << inputStr;基于std::regex C++ 的解决方案:
可以使用以下方法删除数字之间的逗号
std::string inputStr("apple with make,up things $312,412,3.00");
std::regex numRegex(R"((\d),(?=\d))");
std::cout << regex_replace(inputStr, numRegex, "$1") << "\n";
// => apple with make,up things $3124123.00详细信息
(\d) -捕获组1 ($1):一个数字, -逗号(?=\d) -一个积极的前瞻性,需要一个数字立即在当前位置的右边。发布于 2021-04-07 23:22:11
在您尝试的模式中,您正在重复外部组(([0-9]+),)+,它将包含最后一个迭代的值,其中可以匹配一个1+数字和一个逗号。
最后一次迭代将捕获412,,而312,将只匹配。
您正在使用regex,但是如果您有boost可用,您可以使用\G锚点,它可以获得迭代匹配,在上一次匹配结束时断言位置并替换为空字符串。
(?:\$|\G(?!^))\d+\K,(?=\d)模式匹配:
(?:非捕获群\$匹配$|或\G(?!^)在上一场比赛结束时断言位置,而不是在开始时。)闭非捕获群\d+\K匹配1+数字,忘记到目前为止匹配的是什么,(?=\d)匹配一个逗号,并在右边直接断言一个数字#include<iostream>
#include <string>
#include <boost/regex.hpp>
using namespace std;
int main()
{
std::string inputStr = "apple with make,up things $312,412,3.00";
boost::regex numRegex("(?:\\$|\\G(?!^))\\d+\\K,(?=\\d)");
std::string result = boost::regex_replace(inputStr, numRegex, "");
std::cout << result << std::endl;
}输出
apple with make,up things $3124123.00https://stackoverflow.com/questions/66992653
复制相似问题