如何使用 std::regex 查找字符串中的下一个匹配项?
How to use std::regex to find the next match in a string?
正在尝试在扫描仪中使用 std::regex
。因此,在我的例子中,它应该做的就是找到从输入序列的 const char *p
开始的第一个匹配项。它不应该跳过任何东西。只要表达式有效,它就需要匹配。然后return它得到了什么。
这可能吗?
这是我的拙劣尝试:
#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.");
}
我正在寻找的是它只有 returns "500"
作为成功匹配。但我什至无法达到 return true...
相比之下,如果输入 " 500"
它应该 return 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]
。
看到它运行:
https://ideone.com/ChqQIb
这必须与 std::regex_iterator 一起使用,详情请参阅(包括示例)http://en.cppreference.com/w/cpp/regex/regex_iterator
正在尝试在扫描仪中使用 std::regex
。因此,在我的例子中,它应该做的就是找到从输入序列的 const char *p
开始的第一个匹配项。它不应该跳过任何东西。只要表达式有效,它就需要匹配。然后return它得到了什么。
这可能吗?
这是我的拙劣尝试:
#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.");
}
我正在寻找的是它只有 returns "500"
作为成功匹配。但我什至无法达到 return true...
相比之下,如果输入 " 500"
它应该 return 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]
。
看到它运行: https://ideone.com/ChqQIb
这必须与 std::regex_iterator 一起使用,详情请参阅(包括示例)http://en.cppreference.com/w/cpp/regex/regex_iterator