gpt4 book ai didi

c++ - regex_match 给出意想不到的结果

转载 作者:行者123 更新时间:2023-11-28 02:30:53 28 4
gpt4 key购买 nike

我正在尝试编写递归下降解析器,并尝试在用户输入的字符串中搜索正则表达式的匹配项。我正在尝试执行以下操作以尝试理解 <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
+
+

您的代码问题:

  1. regex_match() 返回 false。
  2. 您的正则表达式中没有任何捕获组。因此,即使 regex_match() 返回 true,它也不会捕获任何内容。
  3. regex_match 中的捕获次数可以通过查看正则表达式来严格确定。所以我的 re 将准确捕获一个组。
  4. 但是我们想在我们的字符串上多次应用这个正则表达式,因为我们想找到所有的匹配项。用于此目的的工具是 regex_iterator
  5. 我们还需要转义正则表达式中的-。减号在字符类中具有特殊含义。

关于c++ - regex_match 给出意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29056535/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com