gpt4 book ai didi

C++ 正则表达式匹配 - 拉出匹配的数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:17:58 24 4
gpt4 key购买 nike

好的,所以我正在使用 C++ 正则表达式,但我不太确定如何从表达式中提取我想要的数字。

我正在构建一个基于数字的表达式,但不确定如何将它们拉回来。

这是我的字符串:

+10.7% 是我的字符串 +5 和一些额外的东西

我用那个字符串来提取数字1075 出来并将它们添加到一个 vector 中,没什么大不了的。然后我将该字符串更改为正则表达式。

\+([0-9]+)\.([0-9]+)% 是我的字符串\+([0-9]+) 和一些额外的东西

现在我该如何使用正则表达式来匹配我的起始字符串并提取数字。

与使用匹配表有关吗?

最佳答案

您必须遍历子匹配以提取它们。

例子:

#include <iostream>
#include <string>
#include <regex>

int main()
{
std::string input = "+10.7% Is My String +5 And Some Extra Stuff Here";
std::regex rx("\\+([0-9]+)\\.([0-9]+)% Is My String \\+([0-9]+) And Some Extra Stuff Here");

std::smatch match;

if (std::regex_match(input, match, rx))
{
for (std::size_t i = 0; i < match.size(); ++i)
{
std::ssub_match sub_match = match[i];
std::string num = sub_match.str();
std::cout << " submatch " << i << ": " << num << std::endl;
}
}
}

输出:

 submatch 0: +10.7% Is My String +5 And Some Extra Stuff Here
submatch 1: 10
submatch 2: 7
submatch 3: 5

实例:https://ideone.com/01XJDF

关于C++ 正则表达式匹配 - 拉出匹配的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30750567/

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