gpt4 book ai didi

c++ - std::smatch 返回了什么,你应该如何使用它?

转载 作者:可可西里 更新时间:2023-11-01 16:13:51 24 4
gpt4 key购买 nike

string “我5岁了”

正则表达式 "(?!am )\d"

如果你去http://regexr.com/并将正则表达式应用于您将获得 5 的字符串。我想用 std::regex 得到这个结果,但我不明白如何使用匹配结果,可能 regex 也必须改变。

std::regex expression("(?!am )\\d");
std::smatch match;
std::string what("I am 5 years old.");
if (regex_search(what, match, expression))
{
//???
}

最佳答案

std::smatchmatch_results 的一个实例匹配字符串对象的类模板(使用 string::const_iterator 作为其迭代器类型)。此类的成员是为 match_results 描述的那些成员, 但使用 string::const_iterator作为其 BidirectionalIterator模板参数。

std::match_results 支持 operator[] :

If n > 0 and n < size(), returns a reference to the std::sub_match representing the part of the target sequence that was matched by the nth captured marked subexpression).

If n == 0, returns a reference to the std::sub_match representing the part of the target sequence matched by the entire matched regular expression.

if n >= size(), returns a reference to a std::sub_match representing an unmatched sub-expression (an empty subrange of the target sequence).

在你的例子中,regex_search 只找到第一个匹配项,然后是 match[0]包含整个匹配文本,match[1]将包含使用第一个捕获组(第一个括号括起的模式部分)捕获的文本等。但是在这种情况下,您的正则表达式不包含捕获组。

在这里,你需要使用一个捕获机制,因为std::regex不支持向后看。您使用了前瞻检查当前位置紧跟的文本,而您拥有的正则表达式并没有按照您的想法行事。

因此,使用 following code :

#include <regex>
#include <string>
#include <iostream>
using namespace std;

int main() {
std::regex expression(R"(am\s+(\d+))");
std::smatch match;
std::string what("I am 5 years old.");
if (regex_search(what, match, expression))
{
cout << match.str(1) << endl;
}
return 0;
}

这里的模式是 am\s+(\d+)" .匹配am , 1+ 个空格,然后捕获 1 个或多个数字 (\d+) .在代码中,match.str(1)允许访问使用捕获组捕获 的值。因为只有一个 (...)在模式中,一个捕获组,其 ID 为 1。因此,str(1)返回捕获到该组中的文本。

原始字符串文字 ( R"(...)" ) 允许使用单个反斜杠进行正则表达式转义(如 \d\s 等)。

关于c++ - std::smatch 返回了什么,你应该如何使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44540711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com