【问题标题】:Text Parser c++ code文本解析器 C++ 代码
【发布时间】:2016-04-18 12:18:44
【问题描述】:

我需要一个 C++ 代码来解决以下问题: 我有一个要从特定行开始读取的文本文件,然后我需要打印位于字符之间的输出 --- 例如:你好 我希望输出是你好

我认为我应该使用文本解析器,但不确定如何使用!

#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <fstream>
#include <string>

using namespace std;
int main(int argc, char* argv[])
{

    std::string line_;
    ifstream file_("tty.txt");
    if (file_.is_open())
    {
        while (getline(file_, line_))
        {
            std::cout << line_ << '\n';

        }

        file_.close();

    }
    else
    std::cout << "error" << '\n';
    std::cin.get();
    system("PAUSE");
    return 0;
}

【问题讨论】:

  • 是的,您似乎确实需要解析器。为了解析文本,您尝试做什么?
  • 可能是std::regex 之类的东西?
  • 看不到描述和示例字符串与预期输出之间的关系。您需要在两个 &lt;\s&gt; 内添加文本还是什么?
  • 我的第一个想法也是正则表达式。
  • 如果分隔符是简单的文本,只需搜索它们。 std::string 可以很简单地做到这一点;不需要正则表达式的开销和复杂性。

标签: c++ parsing text


【解决方案1】:

您可以将所有文本加载到一个变量中,然后使用正则表达式搜索所需模式的所有出现(在您的情况下 &lt;sth&gt;(any_aplha_numeric_character)*&lt;/sth&gt; 其中* 表示一个或多个出现,您可以在任何 std::正则表达式教程)

例子:

std::smatch m;          
std::string text = "<a>adsd</a>  <a>esd</a>";
std::string::const_iterator searchStart(text.cbegin());
std::regex rgx("<a>[A-Za-z0-9\\s]*</a>");

while (std::regex_search(searchStart, text.cend(), m, rgx))
{
    cout << m[0] << endl;
    searchStart += m.position() + m.length();
}

给出:&lt;a&gt;adsd&lt;/a&gt;&lt;a&gt;esd&lt;/a&gt; 作为结果,从中提取内部字符串非常容易

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 2015-12-05
    • 1970-01-01
    相关资源
    最近更新 更多