假设我有这段简单的正则表达式搜索代码:
boost::regex re("(\\d+)(/(\\d))?");
boost::smatch matches;
boost::regex_search(input_str, matches, re);
它在字符串中搜索类似 123/2
或 123
的内容。第二个数字和/是可选的。
我想知道 /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/