【问题标题】:Picking up a certain string pattern without regex在没有正则表达式的情况下拾取某个字符串模式
【发布时间】:2015-06-02 03:06:25
【问题描述】:

我有一个场景,我有各种带有特定宏的 C++ 文件:

__EXTERNALIZE(Name, File)

这个宏是空的,它什么也不做。但是我想写一个外部工具来扫描这个宏的一个或多个输入文件,并在找到它后做一些事情。

为了澄清,这里有一点伪c:

typedef struct {
    char* varname;
    char* filename;
} MacroInfo_s;
FILE* fh = fopen("./source.cpp",'r');
while(read_untill_macro(fh) && !feof(fh)) {
    MacroInfo_s m;
    fill_macro_info(&m, fh);
    // Do something with m.varname and m.filename
}

C++11 并未广泛使用。例如,VS 2010 根本不提供它,这是我想在 Windows 端定位的最低版本。在我的 OS X 10.10 上,一切都很好。这也是我主要不想使用 Regexp 的原因,因为我需要一个额外的库。而且仅仅对几个文件中的单个宏做出反应似乎有点过头了。

什么是使这成为可能的好方法?

【问题讨论】:

  • 我不会为此使用 C++,而是使用脚本语言
  • 我会使用grep。你能澄清你为什么要为此编写一个工具吗?您的主要目的似乎是识别包含此宏的源文件并可能将其删除。

标签: c++ regex c++11 macros


【解决方案1】:

我能想到的最简单的方法是使用std::getline 读取每个打开的括号(,然后检查该字符串是否适合您的宏。

然后另一个std::getline 读取到结束括号) 应该提取您的宏的参数。

有点像这样:

const std::string EXTERNALIZE = "__EXTERNALIZE";

int main(int, char* argv[])
{
    for(char** arg = argv + 1; *arg; ++arg)
    {
        std::cout << "Processing file: " << *arg << '\n';

        std::ifstream ifs(*arg);

        std::string text;
        while(std::getline(ifs, text, '('))
        {
            // use rfind() to check the text leading up to the open paren (
            if(text.rfind(EXTERNALIZE) != text.size() - EXTERNALIZE.size())
                continue;

            std::cout << "found macro:" << '\n';

            // now read the parameters up to the closing paren )
            std::getline(ifs, text, ')');

            // here are the macro's parameters
            std::cout << "parameters: " << text << '\n';
        }
    }
}

【讨论】:

  • 整洁!我不知道getline 有这样的权力。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
  • 1970-01-01
  • 2019-08-06
  • 2021-12-16
  • 2017-07-12
相关资源
最近更新 更多