找到$ number,然后将其替换为$ number + 1?

时间:2018-08-02 12:13:23

标签: c++ regex string replace

我想找到$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

是否可以使用正则表达式来做到这一点?

1 个答案:

答案 0 :(得分:1)

考虑以下方法

#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