There is such pattern:
(parse file_name (txt or ini)) or/and (if (string)(== or !=)(string)/* must be at least one */ (and)/*cannot be at the end without expression on right*/)
Explanation: there are two commands – ‘parse’ and ‘if’. There are three cases of mixing these commands:
- ‘parse’ + ‘if’
- ‘parse’
- ‘if’
If ‘parse’ is used then ‘file_name’ must be supplied and ‘txt’ or ‘ini’ can be supplied but doesn’t have to.
If ‘if’ is used then there must be at least one operation ‘string'(‘==’ or ‘!=’)’string’. There can be used more than one operation which are separated by ‘and’, however ‘and’ cannot be used at the end of operations list for example ‘if a==c and b==d and’ – incorrect.
I tried to write following regular expressions, but it doesn’t work:
std::string text = "parse file txt if hello==name and a!=age and owner==me";
boost::regex expr(".*(parse) *(\\w*) *(txt|ini)* *(if) *( *([a-z\"]+)(==|!=)([a-z\"]+) *(and)*)* *");
boost::smatch what;
std::cout << text << std::endl;
if (boost::regex_search(text, what, expr))
for (int j = 0; j < what.size(); ++j)
{
std::cout << what[j] << std::endl;
}
Output:
parse file txt if hello==name and a!=age and owner==me
parse file txt if hello==name and a!=age and
parse
file
txt
if
owner==me
owner
==
me
and
What is the correct regular expression for such case?
You should consider using an actual parser instead of regular expressions. Regular expressions are a powerful tool, but what you’re trying to do is not really what they’re meant for. Either write one yourself (shouldn’t be that hard for the problem at hand), or go looking for a parsing library or parser generator.