从正则表达式匹配中替换另一个特定字符?

时间:2017-03-15 17:50:54

标签: c++ regex string c++11 replace

每当找到*模式时,我都会尝试将替换为\w*\w。这就是我所拥有的

#include <string>
#include <iostream>
#include <regex>

using namespace std;

int main() {
    string text = "Dear Customer, You have made a Debit Card purchase of INR962.00 on 26 Oct. Info.VPS*Brown House. Your Net Available Balance is INR 5,584.58.";

    regex reg("[\w*\w]");
    text = regex_replace(text, reg, " ");
    cout << text << "\n";
}

但它也将*替换为,将w替换为

上述程序的输出是

Dear Customer, You have made a Debit Card purchase of INR962.00 on 26 Oct. Info.VPS Bro n House. Your Net Available Balance is INR 5,584.58.

1 个答案:

答案 0 :(得分:2)

使用

regex reg(R"(([a-zA-Z])\*(?=[a-zA-Z]))");
text = regex_replace(text, reg, "$1 ");
// => Dear Customer, You have made a Debit Card purchase of INR962.00 on 26 Oct. Info.VPS Brown House. Your Net Available Balance is INR 5,584.58.

请参阅C++ online demo

R"(([a-zA-Z])\*(?=[a-zA-Z]))"是原始字符串文字,其中\被视为文字\符号,而不是\n\r等实体的转义符号

模式([a-zA-Z])\*(?=[a-zA-Z])匹配并捕获ASCII字母char(带([a-zA-Z])),然后匹配*(带\*)然后需要(不消耗) ASCII字母字符(带(?=[a-zA-Z]))。

$1是对([a-zA-Z])群体捕获的值的反向引用。