c++ - 如何确定是否捕获了正则表达式的可选部分?

标签 c++ boost boost-regex

假设我有这段简单的正则表达式搜索代码:

boost::regex re("(\\d+)(/(\\d))?");
boost::smatch matches;
boost::regex_search(input_str, matches, re);

它在字符串中搜索类似 123/2123 的内容。第二个数字和/是可选的。
我想知道 /2 是否存在,如果存在,则将/之后的第二个数字设置为变量,否则将变量设置为 -1。
我尝试使用 matches.size(),但无论第二部分是否存在,它始终是相同的值。

最佳答案

组有一个 bool 值 matched 成员,您可以检查。

参见 http://www.boost.org/doc/libs/1_59_0/libs/regex/doc/html/boost_regex/ref/regex_match.html

m[b].matched - For all integers n < m.size(), true if sub-expression n participated in the match, false otherwise.

关于c++ - 如何确定是否捕获了正则表达式的可选部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34177072/

相关文章:

c++ - 通过 char 将 .txt 读入 vector 但不忽略空格

c++ - 将 ASCII EOH 字符表示为字符串?

c++ - 如何编写正则表达式来匹配 ((11 3) (96 15) (2 3) )

c++ - 使用 Boost 的 C++ 中的正则表达式

c++ - std::regex 在 VC2015U3 上比 boost::regex 慢得多

c++ - 使用 RasDial 建立 VPN 连接后,是否要防止网络定位向导弹出?

c++ - 在c++ 17中串联多个std::vector将重复项考虑在内

c++ - 如何在 C++ 中启动具有管理员权限的应用程序?

c++ - 如何构建 Boost::program_options(在 Linux 上)

c++ - boost::mpl::integral_c 之类的模板可以注册到 Boost.Typeof 吗?