Reputation: 2745
I wrote this line fore regex in c++ 11:
regex a("(\\w\\d)+(\\W)?(*)(\\W)?(\\w\\d)+");
I want to find phrase like A * B (A or B could be number) and space are optional
but at this line it throw an exemption! what wrong whit this line of code?
Upvotes: 0
Views: 211
Reputation: 71598
Escape the asterisk (not sure if it should be escaped with a single or double backslashes, but correct me if I'm wrong!):
regex a("(\\w\\d)+(\\W)?(\\*)(\\W)?(\\w\\d)+");
^^
The asterisk is a character in regex to indicate the occurrence of a character or group of characters 0 or more times.
Using (*)
alone isn't valid, and causes the "exception" :)
Still though, to make it work, you need this regex:
regex a("(\\w)+(\\W)?(\\*)(\\W)?(\\w)+");
This should match your string A * B
\w
(or \\w
) in your case matches both numbers and alphabets, so don't worry about using \\d
, because the way you wrote it, it will match one alphanumeric character (or underscore) accompanied with a digit.
Last, if you only want to match and not capture, this should still work:
regex a("\\w+\\W?\\*\\W?\\w+");
Addendum:
regex rx{ R"((\w)+\W?(\*)\W?(\w)+)" };
cout << regex_replace("A * B", rx, "($1$2$3)");
Upvotes: 6
Reputation: 7271
*
is a reserved character in regex that will match a character 0 or many times. You need escape the *
character using \\*
to match the *
symbol
E.g.
regex a("(\\w\\d)+(\\W)?(\\*)(\\W)?(\\w\\d)+");
Upvotes: 1