Regex 使用正则表达式的条件替换
我需要一些使用正则表达式格式化字符串的帮助。我有一个字串 (33,2)、(44,2)、(0,11) 我必须将此字符串重新格式化为以下格式 (2) ,(2),(0,11) 也就是说,从输入中删除Regex 使用正则表达式的条件替换,regex,c++11,Regex,C++11,我需要一些使用正则表达式格式化字符串的帮助。我有一个字串 (33,2)、(44,2)、(0,11) 我必须将此字符串重新格式化为以下格式 (2) ,(2),(0,11) 也就是说,从输入中删除(\\([[:digit:]+\\,),上次出现的除外 我尝试了以下代码,但它替换了所有出现的代码 #include <iostream> #include <string> #include <regex> int main () { std::string s
(\\([[:digit:]+\\,)
,上次出现的除外
我尝试了以下代码,但它替换了所有出现的代码
#include <iostream>
#include <string>
#include <regex>
int main ()
{
std::string s ("(32,33),(63,22),(22,1)");
std::regex e ("[[:digit:]]+\\,");
std::string result;
std::regex_replace (std::back_inserter(result), s.begin(), s.end(), e, "$2");
std::cout << result;
return 0;
}
#包括
#包括
#包括
int main()
{
std::字符串s(“(32,33)、(63,22)、(22,1)”);
std::regex e(“[[:digit:]+\\,”);
std::字符串结果;
std::regex_replace(std::back_inserter(result),s.begin(),s.end(),e,“$2”);
std::cout仅当这些数字后跟(
)时,才可以匹配这些数字:
详细信息:
[[:d:]+
-1位或更多数字
,
-逗号
(?=.\\\\()
-在除换行符以外的任何0+字符之后需要一个(
)的正向前瞻
此处的正向先行可替换为负的(?![:d:]+\\)$)
先行,以使数字+,
的所有匹配失败,如果在字符串末尾后跟1+个数字+)
见:
#包括
#包括
#包括
int main()
{
std::字符串s(“(32,33)、(63,22)、(22,1)”);
std::regex e(“[[:d:][]”+,(?=.\\\()”;
std::字符串结果;
std::regex_replace(std::back_inserter(result),s.begin(),s.end(),e,“$2”);
std::你不想要这个吗?非常感谢。这非常有效。我没有想到使用“(?=*\()”作为检查的条件。新手问题:)
[[:d:]]+,(?=.*\()
#include <iostream>
#include <string>
#include <regex>
int main ()
{
std::string s ("(32,33),(63,22),(22,1)");
std::regex e ("[[:d:]]+,(?=.*\\()");
std::string result;
std::regex_replace (std::back_inserter(result), s.begin(), s.end(), e, "$2");
std::cout << result;
return 0;
}