I want to detect when the user enters "lw 2, 3(9)" , but it can't read the parenthesis, I used this code but it still doesn't detect the parenthesis.
{ R"((\w+) ([[:digit:]]+), ([[:digit:]]+) (\\([[:digit:]]+\\)) )"}
Can someone please help?
I want to detect when the user enters "lw 2, 3(9)" , but it can't read the parenthesis, I used this code but it still doesn't detect the parenthesis.
{ R"((\w+) ([[:digit:]]+), ([[:digit:]]+) (\\([[:digit:]]+\\)) )"}
Can someone please help?
You need to be careful with excessive spaces in the pattern, and since you are using a raw string literal, you should not double escape special chars:
R"((\w+) ([[:digit:]]+), ([[:digit:]]+)(\([[:digit:]]+\)))"
^^^ ^ ^^
It might be a good idea to replace literal spaces with [[:space:]]+
.
C++ demo printing lw 2, 3(9)
:
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
regex rx(R"((\w+) ([[:digit:]]+), ([[:digit:]]+)(\([[:digit:]]+\)))");
string s("Text lw 2, 3(9) here");
smatch m;
if (regex_search(s, m, rx)) {
std::cout << m[0] << std::endl;
}
return 0;
}
R"((\w+) (\d+), (\d+)(\(\d+\)))"
worked for me
Since you didn't specify whether you want to capture something or not, I'll provide both snippets.
You don't have to escape characters with raw string literals but you do have to escape capture groups
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::string str = "lw 2, 3(9)";
{
std::regex my_regex(R"(\w+ \d+, \d+\(\d+\))");
if (std::regex_search(str, my_regex)) {
std::cout << "Detected\n";
}
}
{
// With capture groups
std::regex my_regex(R"((\w+) (\d+), (\d+)(\(\d+\)))");
std::smatch match;
if (std::regex_search(str, match, my_regex)) {
std::cout << match[0] << std::endl;
}
}
}
An additional improvement could be to handle multiple spacing (if that is allowed in your particular case) with \s+
.
I can't help but notice that EJP's concerns might also be spot-on: this is a very fragile solution parsing-wise.