gpt4 book ai didi

c++ - 仅使用 regex_search 返回第一个匹配项

转载 作者:行者123 更新时间:2023-11-27 23:37:33 27 4
gpt4 key购买 nike

我正在尝试使用正则表达式从字符串中提取版本号。版本号的格式为“D.D.Dc”,其中“D”是数字(可以是一个或多个实例),“c”是可选的字母字符,两侧由空格包围。

我想从中提取的字符串是这样的:

FOO 5.1.7d BAR 5.0.2 2019/06/18

我使用的正则表达式是:

\s(\d+)\.(\d+)\.(\d+)([a-zA-Z])?\s

下面是我正在使用的代码。

static regex FWVersionFormat{ R"(\s(\d+)\.(\d+)\.(\d+)([a-zA-Z])?\s)" }; 

auto matches = cmatch{};
if (regex_search(strVersion.c_str(), matches, FWVersionFormat))
{
int maj = 0, min = 0, maint = 0, build = 0;
if (!matches[1].str().empty()) maj = strtol(matches[1].str().c_str(), nullptr, 10);
if (!matches[2].str().empty()) min = strtol(matches[2].str().c_str(), nullptr, 10);
if (!matches[3].str().empty()) maint = strtol(matches[3].str().c_str(), nullptr, 10);
if (!matches[4].str().empty()) build = matches[4].str().c_str()[0] - ('a' - 1);
return{ maj, min, maint, build };
}

如果版本字符串中只有一个匹配项,这会正常工作,但问题是 regex_search() 将版本的第二个实例放入匹配项(“5.0.2”)。

我希望能够只提取第一个匹配项。有没有办法使用正则表达式来做到这一点?

最佳答案

感谢@TheFourthBird 的回答。

我更改了我的正则表达式以在末尾包含否定前瞻,以便搜索在第一个匹配实例处停止。

\s(\d+)\.(\d+)\.(\d+)([a-zA-Z])?\s(?!\d)

关于c++ - 仅使用 regex_search 返回第一个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58186418/

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