尝试在扫描仪中使用 std::regex
。因此,在我的例子中,它应该做的就是找到从输入序列的 const char *p
开始的第一个匹配项。它不应该跳过任何东西。只要表达式有效,它就需要匹配。然后返回它得到的东西。
这可能吗?
这是我的拙劣尝试:
#include <regex>
static void Test()
{
const char *numbers = "500 42 399 4711";
std::regex expr("[0-9]+");
std::match_results<const char *> matches;
if (std::regex_match
(&numbers[0]
,&numbers[strlen(numbers)]
, matches
, expr
, std::regex_constants::match_continuous))
{
printf("match: %s\n", matches[0]);
}
else
puts("No match.");
}
我正在寻找的是它只返回 "500"
作为成功匹配。但我什至无法让它返回 true...
相反,如果输入 "500"
它应该返回 false。
std::regex_search()
似乎也不符合我的要求。它试图找到每一个匹配项,而不仅仅是第一个匹配项。
谢谢。
最佳答案
改变
regex_match
至 regex_search
.第二个参数是多余的:
if (std::regex_search
(numbers
, matches
, expr
, std::regex_constants::match_continuous)) { ... }
还有 matches [0]
不是 C 字符串,而是 std:: sub_match <char const *> const
.您不能将其传递给 printf
没有写这样的东西:
printf ("match: %s", matches[0].str ().c_str ());
它对于流来说是过载的,所以你可以
std:: cout << matches [0]
.
关于c++ - 如何使用 std::regex 查找字符串中的下一个匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28660926/