c++ - 避免来自 Regex_search 的额外匹配

标签 c++

C++ 正则表达式库非常新。

我们正在尝试解析一行

*10 abc

我们想将这一行解析/拆分为两个标记:

10
abc

我尝试了多种方法,例如 regex_search,但我确实得到了 3 个匹配项。第一场比赛是全场比赛,第二场比赛,第三场比赛是子序列比赛。我的问题是

我们怎样才能从上面的字符串中只得到两个匹配项(10 和 abc)。我尝试过的快照:

#include <regex>
#include <iostream>

int main() {
  const std::string t = "*10 abc";
  std::regex rgxx("\\*(\\d+)\\s+(.+)");
  std::smatch match;
  bool matched1 = std::regex_search(t.begin(), t.end(), match, rgxx);
  std::cout << "Matched size " << match.size() << std::endl;

  for(int i = 0 ; i < match.size(); ++i) {
    std::cout << i << " match " << match[i] << std::endl;
  }
}

输出:

Matched size 3
0 match *10 abc
1 match 10
2 match abc

0 匹配是我不想要的。

我也愿意使用 boost 库/正则表达式。谢谢。

最佳答案

您的代码本身没有任何问题。零匹配只是匹配正则表达式模式的整个字符串。如果您只想要两个捕获的术语,则只需打印第一个和第二个捕获组:

const std::string t = "*10 abc";
std::regex rgxx("(\\d+)\\s+(.+)");
std::smatch match;
bool matched1 = std::regex_search(t.begin(), t.end(), match, rgxx);
std::cout << "Matched size " << match.size() << std::endl;

for (int i=1; i < match.size(); ++i) {
    std::cout << i << " match " << match[i] << std::endl;
}

Matched size 3
1 match 10
2 match abc

因此,这里的教训是匹配数组中的第一个条目(索引为零)将始终是整个字符串。

关于c++ - 避免来自 Regex_search 的额外匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53737304/

相关文章:

c++ - CUDA:二维数组索引给出意想不到的结果

c++ - 从列表中的对象更改变量 (c++)

c++ - 有没有更好的方法来处理为层次结构中的类分配身份以供运行时使用?

c++ - 在编译时组合成员

c++ - 从 linux 命令行用另一个替换整个段落

c++ - 在哪里可以找到 Windows 进程中已卸载模块的列表?

c++ - 无符号整数如何工作

C++ 类头 - "error: expected unqualified-id before ' )' token"

c++ - 覆盖时的 GCC 弃用消息

c++ - C++ 中的 Extern (VS2012) 找到多个定义的符号