【问题标题】:Replace a specific character with another from regex match?用正则表达式匹配中的另一个替换特定字符?
【发布时间】:2017-03-15 17:50:54
【问题描述】:

每当找到\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.

【问题讨论】:

  • regex reg(R"((\w)\*(?=\w))"); 并替换为 "$1 "
  • regex [ ] 并不是你想的那样,
  • [\w*\w] 表示替换任何字符w*

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


【解决方案1】:

使用

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 字母字符(带有 ([a-zA-Z])),然后匹配一个 *(带有 \*),然后需要(不消耗)一个 ASCII 字母字符(带有 @987654332 @)。

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

【讨论】:

  • 很好的答案。它还将* 替换为来自32423*randomrandom*34234323423*43421 等我不想要的模式的``。
  • 但是您自己使用了\w。如果您只需要匹配 ASCII 字母之间的*,请改用[a-zA-Z]
猜你喜欢
  • 2023-01-02
  • 2015-11-30
  • 1970-01-01
  • 2015-01-04
  • 1970-01-01
  • 2022-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多