繁体   English   中英

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

[英]Return first match only with regex_search

我正在尝试使用正则表达式从字符串中提取版本号。 版本号采用“DDDc”格式,其中“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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM