Reputation: 185
I'mm starting to learn about Regular Expressions and I have written code in c++
my task is : Implement a function that replaces each digit in the given string with a '@'
character.
For my example, the input
string = "12 points"
.
I know I need to use \d
for matches a digit. I tried to use this : std::regex_replace(input,std::regex("\d"),"@");
but it is not working: the output
is still "12 points"
;
Then I searched the internet and the result is:
std::regex_replace(input,std::regex("\\d"),"@");
with the output
is "@@ points"
.
Can anyone help me to understand what is "\\d"
?
Upvotes: 1
Views: 2956
Reputation: 76434
\d
means decimal, however, in the regular expression, the \
is a special character, which needs to be escaped on its own as well, hence in \\d
you escape the \
to mark it to be used as a regular character instead of its special meaning.
Upvotes: 1
Reputation: 5477
When you use "\d" in a C++ application, the \ is an escape character in C++. So it doesn't treat the following d as a d.
Regex then gets a string that doesn't have \d in it, but most likely an empty string (since \d doesn't evaluate to anything in C++ to my knowledge).
When you use "\d" you are escaping the . So C++ reads the string as "\d" as you intended.
An example of when you'd use an escape character, is when you want to output a quote. "\"" would output a single double quote.
Upvotes: 1