0

I am trying to replace * with whenever \w*\w pattern is found. Here is what I have

#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";
}

But it replace the * with and w with also.

Output of the above program is

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.
3
  • regex reg(R"((\w)\*(?=\w))"); and replace with "$1 " Commented Mar 15, 2017 at 17:55
  • 1
    regex [ ] does not mean what you think it means, Commented Mar 15, 2017 at 17:59
  • [\w*\w] means replace any of the characters w or *. Commented Mar 15, 2017 at 18:01

1 Answer 1

2

Use

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.

See C++ online demo

The R"(([a-zA-Z])\*(?=[a-zA-Z]))" is a raw string literal where \ is treated as a literal \ symbol, not an escaping symbol for entities like \n or \r.

The pattern ([a-zA-Z])\*(?=[a-zA-Z]) matches and captures an ASCII letter char (with ([a-zA-Z])), then matches a * (with \*) and then requires (does not consume) an ASCII letter char (with (?=[a-zA-Z])).

The $1 is the backreference to the value captured with the ([a-zA-Z]) group.

Sign up to request clarification or add additional context in comments.

2 Comments

Great answer. It also replaces the * with ` ` from pattern like 32423*random, random*34234 and 323423*43421 which I don't want.
But you used \w yourself. If you need to only match * in between ASCII letters, use [a-zA-Z] instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.