使用命名捕获可以找出给定正则表达式中命名组的所有名称

Use named capturing to find out all names of named groups in a given regular expression

本文关键字:正则表达式 有名称      更新时间:2023-10-16

我想知道在给定的正则表达式中是否有一个命名捕获组,所以我将使用命名捕获来找出该表达式中的所有名称。

请参阅以下代码片段:

std::string expr = "(?<ns>\S+)";                // (?<ns>S+)
boost::regex re("\(\?\<(?<name>.+)\>");      // (?<(?<name>.+)>
bool found = boost::regex_search(expr, re);      // **found is always false**

我还尝试使用以下两个在线regex测试人员进行验证,他们都工作并找到了"ns"。

  • https://regex101.com
  • http://www.regexplanet.com/advanced/perl/index.html

为什么我的代码不起作用?我是否滥用了boost::regex?

我使用的C++Boost库的版本是1.59

您不应该转义<>。试试这个:

"\(\?<(?<name>.+)>"