c++ - 找到 $number 然后用 $number+1 替换它?
问题描述
我想找到$number
子字符串,然后用$number + 1
格式替换它们。
例如,$1
应该变成$2
一个字符串。
到目前为止,我发现了如何$number
在字符串中查找模式,然后使用正则表达式将它们替换为其他字符串,并且效果很好。
我的代码:
#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
是否可以使用正则表达式来做到这一点?
解决方案
考虑以下方法
#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
推荐阅读
- javascript - 反应原生:有办法显示来自 json 的特定项目吗?
- javascript - 如何在 react-router 中导航到带有百分比符号的路径?
- node.js - 过滤时出现NodeJS String.replace()问题
- jboss - 我们如何使用 jboss cli 从 jboss mq 中删除特定消息
- sql - 通配符运算符用于排除字符前后的所有数字
- java - 如何使用 QueueChannel 和 ServiceActivator 正确配置 TCP inboundAdapter
- c++ - 运行 Linux 的嵌入式 SoC 上的 REST API + Web 服务器
- java - 如何使用带有 CXF 的 WSS 保护 SOAP Web 服务
- react-native - 如果付款成功,如何导航到另一个页面
- mongodb - 在表达式下匹配聚合中的多个条件