我试图编写一个递归下降解析器,并试图在用户输入的字符串中搜索匹配的正则表达式。我正在尝试执行以下操作,以了解C ++ 11提供的<regex>
库,但是得到了意外的结果。
std::string expression = "2+2+2";
std::regex re("[-+*/()]");
std::smatch m;
std::cout << "My expression is " << expression << std::endl;
if(std::regex_search(expression, re)) {
std::cout << "Found a match!" << std::endl;
}
std::regex_match(expression, m, re);
std::cout << "matches:" << std::endl;
for (auto it = m.begin(); it!=m.end(); ++it) {
std::cout << *it << std::endl;
}
因此,根据我的正则表达式,我希望它可以输出
Found a match!
matches:
+
+
但是,我得到的输出是:
My expression is 2+2+2
Found a match!
matches:
我觉得自己犯了一个愚蠢的错误,但是我似乎无法弄清楚为什么输出之间会有差异。
谢谢,
埃里普
最佳答案
您遇到了一些问题。首先,让我们看一些工作代码:
#include <regex>
#include <iostream>
int main() {
std::string expr = "2+2+2";
std::regex re("[+\\-*/()]");
const auto operators_begin = std::sregex_iterator(expr.begin(), expr.end(), re);
const auto operators_end = std::sregex_iterator();
std::cout << "Count: " << std::distance(operators_begin, operators_end) << "\n";
for (auto i = operators_begin; i != operators_end; ++i) {
std::smatch match = *i;
std::cout << match.str() << "\n";
}
}
输出:
Count: 2
+
+
您的代码有问题:
regex_match()
返回false。您在正则表达式中没有任何捕获组。因此,即使
regex_match()
返回true,也不会捕获任何内容。regex_match
中捕获的数量可以通过查看正则表达式严格确定。因此,我将准确地捕获一组。但是我们想在字符串上多次应用此正则表达式,因为我们想找到所有匹配项。该工具是
regex_iterator
。我们还需要在正则表达式中转义
-
。减号在字符类中具有特殊含义。关于c++ - regex_match提供意外结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29056535/