如何从行中提取名称

how can extract the name from a line

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

假设我有一个我想读的文件的行:

>NZ_FNBK01000055.1 Halorientalis regularis    

因此,如何从该行中提取名称,该名称以大于符号开头的线;符号大于符号(不包括在行末尾的新线)的所有内容都是名称。名称应该是:

NZ_FNBK01000055.1 Halorientalis regularis

这是我到目前为止的代码:

bool file::load(istream& file)
{
string line;
while(getline(genomeSource, line)){
    if(line.find(">") != string::npos)
    {
        m_name = 
    }
}
return true;
}

您可以使用正则表达式轻松处理这两种情况。C 在C 11中引入了<regex>。使用此和以下等级类似:

>.*? (.*?) .*$
  • >获取字面角色
  • .*?非贪婪搜索在空间上停止的任何东西 (.*?)非贪婪搜索sor任何东西都停在一个空间上,但请事先将字符分组。
  • .*$贪婪搜索直到字符串结束。

这样,您可以轻松地检查此行是否符合您的条件同时获取名称。这是一个显示其工作的测试。对于代码,C 11 Regex Lib非常简单:

std::string s = ">NZ_FNBK01000055.1 Halorientalis regularis    "; 
std::regex rgx(">.*? (.*?) .*$"); // Make the regex
std::smatch matches;
if(std::regex_search(s, matches, rgx)) { // Do a search
    if (matches.size() > 1) { // If there are matches, print them.
        std::cout << "The name is " << matches[1].str() << "n"; 
    }
}

这是一个现场示例。