我想找到$number
子字符串,然后用$number + 1
格式替换它们。
例如,$1
应该变成字符串中的$2
。
到目前为止,我已经找到了如何在字符串中找到$number
模式,然后使用regex将其替换为其他字符串,并且效果良好。
我的代码:
#include <iostream>
#include <string>
#include <regex>
std::string replaceDollarNumber(std::string str, std::string replace)
{
std::regex long_word_regex("(\$[0-9]+)");
std::string new_s = std::regex_replace(str, long_word_regex, replace);
return new_s;
}
int main()
{
std::string str = "!$@#$34$1%^&$5*$1$!%$91$12@$3";
auto new_s = replaceDollarNumber(str, "<>");
std::cout << "Result : " << new_s << 'n';
}
结果:
Result : !$@#<><>%^&<>*<>$!%<><>@<>
我想要的结果:
Result : !$@#$35$2%^&$6*$2$!%$92$13@$4
使用regex可以做到这一点吗?
考虑以下方法
#include <iostream>
#include <string>
#include <vector>
#include <regex>
using std::string;
using std::regex;
using std::sregex_token_iterator;
using std::cout;
using std::endl;
using std::vector;
int main()
{
regex re("(\$[0-9]+)");
string s = "!$@#$34$1%^&$5*$1$!%$91$12@$3";
sregex_token_iterator it1(s.begin(), s.end(), re);
sregex_token_iterator it2(s.begin(), s.end(), re, -1);
sregex_token_iterator reg_end;
vector<string> vec;
string new_str;
cout << s << endl;
for (; it1 != reg_end; ++it1){
string temp;
temp = "$" + std::to_string(std::stoi(it1->str().substr(1)) + 1);
vec.push_back(temp);
}
int i(0);
for (; it2 != reg_end; ++it2)
new_str += it2->str() + vec[i++];
cout << new_str << endl;
}
结果是
!$@#$34$1%^&$5*$1$!%$91$12@$3
!$@#$35$2%^&$6*$2$!%$92$13@$4