如何使用 std::regex 查找字符串中的下一个匹配项
How to use std::regex to find the next match in a string?
尝试在扫描仪中使用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: %sn", matches[0]);
}
else
puts("No match.");
}
我正在寻找的是它只返回"500"
作为成功的匹配。但我什至无法让它返回真实...
相反,如果输入" 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]
.
看它运行:https://ideone.com/ChqQIb
这必须与 std::regex_iterator 有关,请参阅有关详细信息(包括示例(http://en.cppreference.com/w/cpp/regex/regex_iterator
相关文章:
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 如何检查一个c++字符串中有多少相同的字符/数字
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- C++自定义流操纵器,用于更改流上的下一个字符串
- 如何在没有运算符>>的情况下从字符串流返回下一个令牌?
- 快速从文件中读取下一个字符串,而无需移动文件的位置
- 如何使用字符串字符数组中的 ++ 运算符访问下一个字符串
- 使用getline()将字符串输入到程序中会导致下一个输入出现某种溢出
- 试图在字符串中找到一个数字,更改它,放回并找到下一个数字
- 为什么一个指向char的C++指针在缺少null终止符的情况下充当字符串
- strtok() - 为什么必须传递 NULL 指针才能获取字符串中的下一个标记
- 按字典顺序从范围中获取下一个数字(不包含所有字符串的容器)
- 如何在字符串中的任意位置提取下一个整数
- 如何使用 std::regex 查找字符串中的下一个匹配项
- 虽然循环不输出子字符串的下一个实例
- std::out_of_range basic_string 当从 vector 中的空字符串转到下一个元素时
- 如何在不使用 variable_name.at() 的情况下引用字符串的最后一个字符
- 如何在C++中的字符串数组中找到下一个空闲元素,然后将数据附加到它
- 检查>>提取的下一个值是字符串还是整数
- 多次调用返回字符串的Lua函数.如何使它有跨到下一个实例的字段