gpt4 book ai didi

c++ - 为什么 regex_match 与我的正则表达式不匹配?

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

我必须编写一个 C++ 正则表达式,但我无法在 regex_match 上获得正确的结果,因为我是 C++ 的新手。测试字符串为:D10A7;让我们说 unsigned_char[] stringToBeTested="D10A7";我要做的是在 regex_match 之后,我将在两个不同的短变量中提取 10 和 7 以供应用程序使用。 'D' 之后的数字总是两位数,'A' 之后的数字总是是一位数。我的尝试是:

boost::regex re("D([0-9])(/([0-9]))?");
boost::cmatch mr;
if ( boost::regex_match(stringToBeTested, mr, re ) )
{
number = atoi(mr.str(1).c_str()); //Must be 10
axis = atoi(mr.str(2).c_str()); //Must be 7
}

如何为这种情况生成boost::regex re,请详细解释答案。

最佳答案

regex_match 需要完整的字符串匹配。您需要提供一个模式来执行此操作。

boost::regex re("D([0-9]{2})A([0-9])");

在这里,

  • D - 匹配 D
  • ([0-9]{2}) - 捕获第 1 组两位数
  • A - 匹配 A
  • ([0-9]) - 将单个数字捕获到第 2 组。

参见 online demo of the above regex .

关于c++ - 为什么 regex_match 与我的正则表达式不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43090952/

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