C 正则是从脚本文件中提取变量

C++ regex to extract variables from a scripting file

本文关键字:文件 提取 变量 脚本      更新时间:2023-10-16

所以我有一个脚本文件,其中使用#符号分配了一些变量,然后是分配操作员(=),然后是字符串。所有这些都是没有空间的。有时,会有评论(从符号开始)或一些额外的空格。例如:

#mat=3     !mat denotes a material number

我想使用C 的Regex实用程序来提取'#mat'和'3'。我无法弄清楚正则模式。即使我有模式,我也不知道如何专门从该行提取" #mat"answers" 3"。当我将COUT用于Regex_search的Smatch阵列时,我会得到整个行。

有什么建议吗?非常感谢您的帮助/建议。

#include <regex>
#include <iostream>
int main()
{
    const std::string s = "#mat=3     !mat denotes a material number";
    std::regex rgx("#(\w+)=(\d+)");
    std::smatch match;
    if (std::regex_search(s.begin(), s.end(), match, rgx))
        std::cout  << match[1]<<"  "<<match[2]<< 'n';
}

组0代表整个正则:#(\w+)=(\d+)

组1,2表示正则第一个和第二个子组:(\w+)(\d+)

因此,match[0]将返回正则竞赛,而match[1]将返回REGEX的第一个子组,即(\w+)match[2]将返回ROGEX的第二个子组,即(\d+)

\d+是指匹配,直到字数字中的最后一次出现。

输出是mat 3

使用C 14。

编译