【问题标题】:Numbered back reference followed by literal number编号的后向引用,后跟文字编号
【发布时间】:2014-11-24 07:33:48
【问题描述】:

我正在尝试执行正则表达式替换。我似乎无法弄清楚的具体问题是,在我的第二个反向引用之后,我有一个字符串文字数字(数字一)。使用 MS Visual Studio 2012(C++ 控制台项目...不是 .NET),它不起作用。我假设是因为它将我的反向引用设为 21 美元,而不是 2 美元。我尝试了各种语法,但无法提出可行的方法!

std::string input = "my_variable_name_iei_lo1";
std::string regx = "(\\w+)iei_(lo_hi)1";
std::string sub = "$1ied_$21";

std::regex rx(regx);

std::string result = std::regex_replace(input, rx, sub);

// result is "my_variable_name_ied_"
// should be "my_variable_name_ied_lo1"

我尝试了各种指定反向引用的方法:

std::string sub = "$1ied_${2}1";

// result is "my_variable_name_ied_${2}1"
// should be "my_variable_name_ied_lo1"

其他事情给了我语法错误,包括尝试使用命名捕获组,但后来读到不再支持。如此接近我的答案,但仍然如此遥远!

【问题讨论】:

  • 无法复制。我使用了"$1ied_$21",得到了"my_variable_name_iei_lo1"。我也在使用 Visual Studio 2012。
  • 根据www.cplusplus.com/reference$n: n-th backreference (i.e., a copy of the n-th matched group specified with parentheses in the regex pattern). n must be an integer value designating a valid backreference, greater than 0, and of two digits at most.。所以,正如乔纳森所说,我会尝试$021,它必须被解析为$02,然后是1
  • 使用 $021 成功了!我知道两位数的限制(99 个捕获组),但无论出于何种原因,从未想过尝试 01、02 等。因此,将替换字符串设置为“$01ied_$021”可以得到我正在寻找的结果。谢谢!

标签: c++ regex visual-studio-2012


【解决方案1】:

Gunn找到的解决方案:

Using $021 worked! I knew about the two digit limitation (99 capture groups)
but for whatever reason, never thought to try 01, 02, etc. So having the substitution
string be "$01ied_$021" gives me the result I was looking for. Thanks!

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 1970-01-01
    • 2020-09-21
    • 2012-03-01
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多