【问题标题】:Find $number and then replace it with $number+1?找到 $number 然后用 $number+1 替换它?
【发布时间】:2019-01-10 05:03:00
【问题描述】:

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

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

【问题讨论】:

  • 看来您可以将this solution 移植到C++。
  • 您可能可以使用捕获组来执行此操作,然后解析每个捕获以获取数字并对其进行处理。或者使用比正则表达式更简单的技术并手动解析输入。记住这句话:“我有一个问题。我用正则表达式解决了它。现在我有两个问题”。在大多数情况下,正则表达式就像用猎枪杀死一只蚊子。它可能有效,但有很多附带损害。
  • 我肯定会从一两个非正则表达式解决方案开始。
  • 首先逐个字符地循环输入字符串。添加将字符(一个接一个)复制到新字符串。添加识别美元字符'$'。在'$' 之后添加数字检查。在'$' 之后添加获取所有数字(不复制它们)。添加将数字字符转换为整数值。将 1 添加到该值。添加将新值作为字符串插入目标。完毕。 :)

标签: c++ regex string replace


【解决方案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

【讨论】:

    猜你喜欢
    • 2012-10-20
    • 2016-11-15
    • 2019-07-29
    • 2015-04-23
    • 1970-01-01
    • 2018-02-05
    • 2020-01-14
    • 1970-01-01
    相关资源
    最近更新 更多