作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试编写递归下降解析器,并尝试在用户输入的字符串中搜索正则表达式的匹配项。我正在尝试执行以下操作以尝试理解 <regex>
C++11 提供的库,但我得到了意想不到的结果。
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
中的捕获次数可以通过查看正则表达式来严格确定。所以我的 re 将准确捕获一个组。regex_iterator
。-
。减号在字符类中具有特殊含义。关于c++ - regex_match 给出意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29056535/
我是一名优秀的程序员,十分优秀!